1.按照字母顺序排序字符串
/**
* String sort(不区分大小写)
*/
private static void sortStringInsentive() {
List<String> originalList = Arrays.asList("Apache", "apache", "aapache", "bpache", "Bpache", "bapache");
originalList.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(originalList);
}
/**
*String sort(区分大小写)
*/
private static void sortStringSentive() {
List<String> originalList = Arrays.asList("Apache", "apache", "aapache", "bpache", "Bpache", "bapache");
originalList.sort(Comparator.naturalOrder());
System.out.println(originalList);
}
2.对数字进行排序
/**
*Integer sort()
*/
private static void sortInteger() {
List<Integer> originalList = Arrays.asList(12, 3, 6, 7);
originalList.sort(Comparator.naturalOrder());
System.out.println(originalList);
}
3.按照对象中中的某个字段进行排序
/**
* bean 中的某个字段 (String)
*/
private static void sortBeanString() {
List<Student> originalList = Arrays.asList(new Student("张三", 24, 23.01, false), new Student("李四", 23, 23.02, true),
new Student("alice", 25, 25.02, false), new Student("Jack", 29, 24, true), new Student("Jack", 28, 24, false),
new Student("mark", 30, 24, false));
originalList.sort(Comparator.comparing(Student::getName).reversed());
System.out.println(originalList);
}
/**
* bean 中的某个字段 (Double)
*/
private static void sortBeanDouble() {
List<Student> originalList = Arrays.asList(new Student("张三", 24, 23.01, false), new Student("李四", 23, 23.02, true),
new Student("alice", 25, 25.02, false), new Student("Jack", 29, 24, true), new Student("Jack", 28, 24, false),
new Student("mark", 30, 24, false));
originalList.sort(Comparator.comparingDouble(Student::getSalary));
System.out.println(originalList);
}
4.按照对象中中的多个字段进行排序
private static void sortBeanMutil() {
List<Student> originalList = Arrays.asList(new Student("张三", 24, 23.01, false), new Student("李四", 23, 23.02, true),
new Student("alice", 25, 25.02, false), new Student("Jack", 29, 24, true), new Student("Jack", 28, 24, false),
new Student("mark", 30, 24, false));
originalList.sort(Comparator.comparingDouble(Student::getSalary).reversed().thenComparing(Comparator.comparingInt(Student::getAge)));
System.out.println(originalList);
}
5.自定义比较器
private static void sortOther() {
List<Student> originalList = Arrays.asList(new Student("张三", 24, 23.01, false), new Student("李四", 23, 23.02, true),
new Student("alice", 25, 25.02, false), new Student("Jack", 29, 24, true), new Student("Jack", 28, 24, false),
new Student("mark", 30, 24, false));
// method 1
originalList.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if (o1.leader == o2.leader) {
return 0;
}
return o1.leader ? -1 : 1;
}
});
System.out.println(originalList);
System.out.println("************************************");
// method 2
originalList.sort((s1, s2) -> {
return s1.isLeader() ? -1 : 1;
});
System.out.println("self 2 :" + originalList);
}