使用lambda表达式对一维数组进行排序,不能直接用int,只能用Integer包装类
希望有大佬可以指导一下菜鸡
Integer[] nums = new Integer[]{1,2,3,4,5};
System.out.println("原数组:1,2,3,4,5");
Arrays.sort(nums, (a, b)->b-a); // 逆序排列
System.out.print("逆序排列:");
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
System.out.println();
System.out.print("正序排列:");
Arrays.sort(nums, (a, b)->a-b); // 正序排列
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
二维数组排序
a[0]是左边元素 a[1]是右边元素
// 左边相同 右边升序
int[][] nums2 = new int[][] {{0, 30}, {15, 20}, {5, 10}, {-10, 20},{-10, 10}};
Arrays.sort(nums2, (a, b) -> {
if(a[0] == b[0]) return a[1] - b[1];
return a[0] - b[0];
});
for (int i = 0; i < nums2.length; i++) {
System.out.println(nums2[i][0] + " " + nums2[i][1]);
}
// 右边相同,左边升序
int[][] nums3 = new int[][] {{0, 30}, {15, 20}, {5, 10}, {-10, 20},{-10, 10}};
Arrays.sort(nums3, (a, b) -> {
if(a[1] == b[1]) return a[0] - b[0];
return a[1] - b[1];
});
for (int i = 0; i < nums3.length; i++) {
System.out.println(nums3[i][0] + " " + nums3[i][1]);
}