环境:java8
public static void lam3() {
//一般操作: 将字符串按照 长度降序排列List<String> list = Arrays.asList("aaaaaa","bbbb","cc","dd","f");
// list.sort((s1,s2)->Integer.compare(s1.length(), s2.length()));
System.out.println(list);
//其实还可以进一步简化 直接接受一个需要排序的字段,底层会调用上面的方法
// public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
// list.sort(Comparator.comparing(s->s.length()));
// list.sort(Comparator.comparingInt(s->s.length()));
list.sort(Comparator.comparingInt(String::length));
System.out.println(list);
}
//按照年龄排序,相同的按照工资升序排序
@Test
public void lam4() {
List<Employee> list=Arrays.asList(
new Employee("小明", 12, 8000),
new Employee("詹丹", 84, 7000),
new Employee("菲菲", 36, 7500),
new Employee("君君", 36, 5000),
new Employee("洋洋", 12, 6000)
);
list.sort(Comparator.comparingInt(Employee::getAge)
.reversed()
.thenComparingDouble(Employee::getSalary));
list.forEach(System.out::println);
}