繁体   English   中英

根据int数组的第一个和第二个元素对int数组的数组列表进行排序

[英]sorting an array list of int arrays in terms of the first and the second element of the int arrays

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

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

例如,以上代码行应修改为(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数组的数组列表进行排序。 在第一个元素相同的情况下如何考虑第二个元素的情况下如何对其进行修改?

谢谢。

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

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM