【问题标题】:sorting an array list of int arrays in terms of the first and the second element of the int arrays根据 int 数组的第一个和第二个元素对 int 数组的数组列表进行排序
【发布时间】:2016-09-05 02:35:28
【问题描述】:
ArrayList<int[]> segment = new Arraylist<int[]>();
segment.add(new int[]{2,3,1});
segment.add(new int[]{2,1,1});
segment.add(new int[]{1,1,1});
segment.add(new int[]{2,4,1});
segment.add(new int[]{3,3,1});

我想要做的是根据每个数组的第一个元素对这个 ArrayLists 进行排序,如果元素相同,则根据数组/数组的第二个元素进行排序

例如上面的代码行应该修改为, (1,1,1) (2,1,1) (2,3,1) (2,4,1) (3,3,1)

这就是我目前解决这个问题的方法,

    public static void SortSegment(ArrayList<int[]> segment){
        Collections.sort(segment, new Comparator<int[]>() {
             public int compare(int[] a, int[] b) {
                  return (a[0] - b[0]);
             }
        });
    }

这段代码根据每个 int 数组的第一个元素对 int 数组的 arraylist 进行排序。 我如何修改它以适用于第一个元素相同的情况,以便考虑第二个元素?

谢谢。

【问题讨论】:

  • 每个 int 数组中是否总是有 3 个元素?
  • 首先检查第一个元素是否相等。如果是,请比较第二个。否则保留你所拥有的。

标签: java arrays sorting arraylist


【解决方案1】:

Comparator 接口在 Java 8 中有一些有用的实用程序(默认)方法,可用于自定义排序:

segment.sort(Comparator.comparingInt(el -> el[0]).thenComparingInt(el -> el[1]));

【讨论】:

    【解决方案2】:

    试试这个

    if(a[0] - b[0]==0) //Like the first row of the matrix if so, we proceed to the next to know which is lower
    

    代码完成

    Collections.sort(segment, new Comparator<int[]>() {
             public int compare(int[] a, int[] b) {
                  if(a[0] - b[0]==0) //if equals
                  {
                      return a[1]-b[1];//recompare 
                  }
                  else
                      return a[0]-b[0];
             }
        });
    

    【讨论】:

      【解决方案3】:

      试试这个:

      segments.sort(Comparator.comparingInt(a -> a[0])
          .thenComparing(a -> a[1])
          .thenComparing(a -> a[2]));
      

      【讨论】:

        猜你喜欢
        • 2013-04-30
        • 2012-03-29
        • 1970-01-01
        • 2020-11-19
        • 2018-11-18
        • 2011-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多