本文共 2378 字,大约阅读时间需要 7 分钟。
转自:
以前的排序一般对象实现Comparable或者Comparator接口,经常是通过匿名类类实现。
可以参见以前的博文 Java 中 Comparable 和 Comparator 比较 现在看看使用lamda表达式和java8中增强的Comparator接口进行排序。先定义一个简单的实体类:
class Human { private String name; private int age; public Human() { super(); } public Human(final String name, final int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}
lamda表达式
Listhumans = new ArrayList<>();humans.add(new Human("Sarah", 10));humans.add(new Human("Jack", 12));humans.sort((Human h1, Human h2) -> h1.getName().compareTo(h2.getName()));//humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));//简化
当然lamda表达式也可以使用静态方法的引用代替。
public static int compareByNameThenAge(Human lhs, Human rhs) { if (lhs.name.equals(rhs.name)) { return lhs.age - rhs.age; } else { return lhs.name.compareTo(rhs.name); }}Listhumans = new ArrayList<>();humans.add(new Human("Sarah", 10));humans.add(new Human("Jack", 12));humans.sort(Human::compareByNameThenAge);
Listhumans = new ArrayList<>();humans.add(new Human("Sarah", 10));humans.add(new Human("Jack", 12));Collections.sort(humans, Comparator.comparing(Human::getName));
还可以使用反转
Collections.sort(humans, Comparator.comparing(Human::getName).reversed());
Listhumans = new ArrayList<>();humans.add(new Human("Sarah", 10));humans.add(new Human("Jack", 12));humans.add(new Human("Jack", 10));humans.sort((lhs, rhs) -> { if (lhs.getName().equals(rhs.getName())) { return Integer.compare(lhs.getAge(), rhs.getAge()); } else { return lhs.getName().compareTo(rhs.getName()); } });
Listhumans = new ArrayList<>();humans.add(new Human("Sarah", 10));humans.add(new Human("Jack", 12));humans.add(new Human("Jack", 10));humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));
转载地址:http://rradi.baihongyu.com/