1.按照字母順序排序字符串
/**
* String sort(不區(qū)分大小寫)
*/
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(區(qū)分大小寫)
*/
private static void sortStringSentive() {
List<String> originalList = Arrays.asList("Apache", "apache", "aapache", "bpache", "Bpache", "bapache");
originalList.sort(Comparator.naturalOrder());
System.out.println(originalList);
}
2.對(duì)數(shù)字進(jìn)行排序
/**
*Integer sort()
*/
private static void sortInteger() {
List<Integer> originalList = Arrays.asList(12, 3, 6, 7);
originalList.sort(Comparator.naturalOrder());
System.out.println(originalList);
}
3.按照對(duì)象中中的某個(gè)字段進(jìn)行排序
/**
* bean 中的某個(gè)字段 (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 中的某個(gè)字段 (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.按照對(duì)象中中的多個(gè)字段進(jìn)行排序
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);
}