Java数组和ArrayList的一些排序的方法
数组排序
//将数组从小到大排序
public static void ArraySortSTB(int[] array){
Arrays.sort(array);
}
//将数组从大到小排序
//1.重写Compare方法 参数必须为类的数组
public static void ArraySortBTS1(Integer[] array){
Arrays.sort(array, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
}
//2.将Array.sort排序后的数组转化顺序
public static void ArraySortBTS2(int[] array){
Arrays.sort(array);
int S=0;
int E=array.length-1;
while(S<E){
int num=array[S];
array[S]=array[E];
array[E]=num;
S++;
E--;
}
}
ArrayList排序
//对集合进行排序
//1.对集合进行升序排列
public static void ListSortSTB(ArrayList<Integer> list){
//https://blog.csdn.net/hzr0523/article/details/82851376 compareTo函数
// list.sort((integer, anotherInteger) -> integer.compareTo(anotherInteger));
// list.sort(Integer::compareTo);
// list.sort(Comparator.naturalOrder()); //以上三种方法等价
//或者
// Collections.sort(list);
//或者
// Collections.sort(list,(o1,o2)->o1-o2);//等价于下面
Collections.sort(list, new Comparator<Integer>(){
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
}
//2.对集合进行降序排列
public static void ListSortBTS(ArrayList<Integer> list){
list.sort((integer, anotherInteger) -> anotherInteger.compareTo(integer));
// Collections.sort(list,(o1, o2) -> o2-01);
// list.sort(Comparator.reverseOrder());
}