根据整型数组的第一个和第二个元素对整型数组的数组列表排序


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});

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

例如,上面的代码行应该修改为:(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数组的数组列表进行排序。我如何修改它的工作情况下,第一个元素是相同的,所以它考虑到第二个元素?

谢谢。

try this

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];
         }
    });

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

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

试试这个:

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

最新更新