英文:
java 2d array secondary sort
问题
我想对以下的二维数组进行排序,使得每行的第一个索引递增,如果两行的第一个索引相同,则第二个索引也按递增排序。例如:
给定:
int[][] arr = new int[][]{{2,5},{2,3},{2,1},{2,4},{2,2},{1,2},{1,1},{1,4},{1,3},{1,5}};
我希望得到 arr = {{1,1},{1,2},{1,3},{1,4},{1,5},{2,1},{2,2},{2,3},{2,4},{2,5}};
我已经成功通过以下方式按第一个索引排序:
Arrays.sort(arr, Comparator.comparingInt(arr -> arr[0]));
现在我的想法是将其拆分为子数组,对它们进行排序,然后将它们合并在一起,但我真的想知道是否有更好的方法,我可能不知道。(也许甚至可以使用比较器,提前谢谢您的帮助)
英文:
I want to sort the following 2D array so, that the first index of each row is ascending and if it is the same in 2 rows, that the second index also is sorted ascending. Example:
given:
int[][] arr = new int[][]{{2,5},{2,3},{2,1},{2,4},{2,2},{1,2},{1,1},{1,4},{1,3},{1,5}};
I want it to be arr = {{1,1},{1,2},{1,3},{1,4},{1,5},{2,1},{2,2},{2,3},{2,4},{2,5}};
It worked for me to sort by first index using:
Arrays.sort(arr, Comparator.comparingInt(arr -> arr[0]));
Now my idea was to cut it down into sub-arrays, sort them and merge them back together, but i really wanted to know if there is a better way to do it I am not aware of. ( maybe even using the comparator, thx in advance )
答案1
得分: 3
你可以通过使用 thenComparing
为第一个比较器添加第二个比较器,这基本上会导致这样的行为:如果第一个比较器返回相等的结果,则使用第二个比较器来解决平局:
int[][] arr2 = new int[][]{{2,5},{2,3},{2,1},{2,4},{2,2},{1,2},{1,1},{1,4},{1,3},{1,5}};
Comparator<int[]> first = Comparator.comparingInt(a -> a[0]);
Comparator<int[]> second = Comparator.comparingInt(a -> a[1]);
Arrays.sort(arr2, first.thenComparing(second));
for (int i = 0; i < arr2.length; i++) {
System.out.println(arr2[i][0] + "," + arr2[i][1]);
}
还可以通过使用 thenComparingInt
来创建更简洁的比较器版本:
Comparator<int[]> cp = Comparator.<int[]>comparingInt(a -> a[0]).thenComparingInt(a -> a[1]);
英文:
you can add a second comparator to the first one by using thenComparing
, which basically leads to a behaviour that if the first comparator returns an equal result the second comparator is used to break the tie:
int[][] arr2 = new int[][]{{2,5},{2,3},{2,1},{2,4},{2,2},{1,2},{1,1},{1,4},{1,3},{1,5}};
Comparator<int[]> first = Comparator.comparingInt(a -> a[0]);
Comparator<int[]> second = Comparator.comparingInt(a -> a[1]);
Arrays.sort(arr2, first.thenComparing(second));
for(int i = 0; i< arr2.length; i++){
System.out.println(arr2[i][0] + "," + arr2[i][1]);
}
it is also possible to create a more succinct version of the comparator, by using thenComparingInt
:
Comparator<int[]> cp = Comparator.<int[]>comparingInt(a -> a[0]).thenComparingInt(a -> a[1]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论