一、对一维数组使用
1.对数组从小到大进行升序排序
Arrays.sort(int[] a)
🌰
public static void main(String[] args) {
int[] nums={1,3,5,7,9,2,4,6,8,10};
Arrays.sort(nums);
for (int num:nums) {
System.out.print(num+" ");
}
}
//结果:1 2 3 4 5 6 7 8 9 10
2.对数组的部分内容进行从小到大排序
Arrays.sort(int[] a, int fromIndex, int toIndex)
🌰
public static void main(String[] args) {
int[] nums={1,3,5,7,9,2,4,6,8,10};
Arrays.sort(nums,1,9);
for (int num:nums) {
System.out.print(num+" ");
}
}
//结果:1 2 3 4 5 6 7 8 9 10
3.重写比较器,实现从大到小排序
🌰
public class MyComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if(o1<o2)
return 1;
else if(o1>o2)
return -1;
else
return 0;
}
}
public class Solution {
public static void main(String[] args) {
Integer[] nums={1,3,5,7,9,2,4,6,8,10};
Comparator cmp=new MyComparator();
Arrays.sort(nums,cmp);
for (int num:nums) {
System.out.print(num+" ");
}
}
}
//结果:10 9 8 7 6 5 4 3 2 1
🐒Comparator源码
@FunctionalInterface
public interface Comparator<T> {
/**
* Compares its two arguments for order. Returns a negative integer,
* zero, or a positive integer as the first argument is less than, equal
* to, or greater than the second.
* 译:对两个参数进行排序,当第一个参数<、=、>第二个参数时,分别返回负数、0、正数。
*/
int compare(T o1, T o2);
}
默认的Comparator比较器对于两个操作数o1,o2
对两个参数进行排序,当第一个参数<、=、>第二个参数时,分别返回负数、0、正数。
现在改写为当第一个参数<第二个参数时,返回正数。
🔵lambda表达式
public class Solution {
public static void main(String[] args) {
Integer[] nums={1,3,5,7,9,2,4,6,8,10};
Arrays.sort(nums,((o1, o2) -> (o2-o1)));
for (int num:nums) {
System.out.print(num+" ");
}
}
}
//结果:10 9 8 7 6 5 4 3 2 1
二、对二维数组使用
1.第一个元素升序排序
public class Solution {
public static void main(String[] args) {
int[][] nums={{1,3},{3,1},{5,4},{2,2}};
Arrays.sort(nums,((o1, o2) -> (o1[0]-o2[0])));
for(int i=0;i< nums.length;i++)
System.out.println(Arrays.toString(nums[i]));
}
}
2.第一个元素降序排序
Arrays.sort(nums,((o1, o2) -> (o2[0]-o1[0])));
3.按照第二个元素升序排序
Arrays.sort(nums,((o1, o2) -> (o1[1]-o2[1])));
4.按照第二个元素降序排序
Arrays.sort(nums,((o1, o2) -> (o2[1]-o1[1])));
觉得本篇对您有帮助的,请留下一个大大的👍🏼赞,这对我真的很重要!