基本数据类型排序
// 升序
int[] arr1 = {45, 34, 59, 55};
Arrays.sort(arr1);
System.out.println(Arrays.toString(arr1));
// 降序,没有专门的降序api,手动反序
int[] arr2 = {45, 34, 59, 55};
Arrays.sort(arr2);
// 翻转数组
for (int i = 0; i < arr2.length / 2; i++) {
int t = arr2[i];
arr2[i] = arr2[arr2.length - i - 1];
arr2[arr2.length - i - 1] = t;
}
System.out.println(Arrays.toString(arr2));
基本数据类型包装类
// 升序
Integer[] arr3 = {45, 34, 59, 55};
Arrays.sort(arr3);
System.out.println(Arrays.toString(arr3));
// 降序
Integer[] arr4 = {45, 34, 59, 55};
Arrays.sort(arr4, (o1, o2) -> o2 - o1);
System.out.println(Arrays.toString(arr4));
普通List
List<Integer> list = Arrays.asList(2, 1, 3);
List<Integer> list1 = Arrays.asList(2, 1, 3);
// 升序
Collections.sort(list);
System.out.println(list);
// 降序
Collections.reverse(list1);
System.out.println(list1);
String类型是按照字符串的比较,不是数字的比较
List<String> list2 = Arrays.asList("122", "33", "56");
Collections.sort(list2);
System.out.println(list2);
对象List
实体类
@Data
public class Person {
private String userName;
private Boolean boss;
private Date birth;
private Integer age;
public Person(String userName, Boolean boss, Integer age) {
this.userName = userName;
this.boss = boss;
this.age = age;
}
}
排序
@Test
public void test3() {
Person person = new Person("111", true, 111);
Person person1 = new Person("111", true, 555);
Person person2 = new Person("333", false, 111);
Person person3 = new Person("444", false, 222);
Person person4 = new Person("111", false, 333);
Person person5 = new Person("111", false, 444);
Person person6 = new Person("111", true, 444);
List<Person> list = Arrays.asList(person, person1, person2, person3,person4,person5,person6);
// 按照userName升序排序
List<Person> ascList = list.stream().sorted(Comparator.comparing(Person::getUserName)).collect(Collectors.toList());
// 按照userName降序排序
// 方法一,Comparator.comparing(类::属性).reversed()表示按照前面的排序结果进行整个列表反序
List<Person> descList = list.stream().sorted(Comparator.comparing(Person::getUserName).reversed()).collect(Collectors.toList());
// 方法二,Comparator.comparing(类::属性,Comparator.reverseOrder())表示按照某属性降序排序(用这个!)
List<Person> descList2 = list.stream().sorted(Comparator.comparing(Person::getUserName, Comparator.reverseOrder())).collect(Collectors.toList());
// 多字段排序
List<Person> collect = list.stream()
.sorted(Comparator.comparing(Person::getUserName)
.thenComparing(Person::getAge, Comparator.reverseOrder())
.thenComparing(Person::getBoss)
)
.collect(Collectors.toList());
System.out.println(collect);
}
userName升序排序
userName降序排序
userName升序排序,age降序…