[英]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.