简体   繁体   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});

What I want to do is sort this ArrayLists according to the first element of each array and if the element is same do the sorting according to the 2nd element of the array/arrays 我想要做的是根据每个数组的第一个元素对此ArrayList进行排序,如果元素相同,则根据数组的第二个元素进行排序

For instance the above lines of code should be modified to, (1,1,1) (2,1,1) (2,3,1) (2,4,1) (3,3,1) 例如,以上代码行应修改为(1,1,1)(2,1,1)(2,3,1)(2,4,1)(3,3,1)

this is what i have so far in temrs of solving this, 这是我到目前为止解决这个问题的方法,

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

this piece of code sorts the arraylist of int arrays according to the first element of each of the int arrays. 这段代码根据每个int数组的第一个元素对int数组的数组列表进行排序。 How do i modify it to work for cases where the first element is the same so it takes into consideration the 2nd element? 在第一个元素相同的情况下如何考虑第二个元素的情况下如何对其进行修改?

thanks. 谢谢。

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

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

Try this: 尝试这个:

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

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

code complete 代码完成

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