java集合根据值排序
意识到Java 8将在接下来的几周内发布其GA版本之后,我认为现在是时候来看看它了,在过去的一周里,我一直在阅读Venkat Subramaniam的书 。
我要讲的是第3章,它涉及对人员集合进行排序。 Person类的定义大致如下:
static class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return String.format("Person{name='%s', age=%d}", name, age);
}
}
在第一个示例中,我们列出了人员列表,然后按年龄升序对其进行排序:
List<Person> people = Arrays.asList(new Person("Paul", 24), new Person("Mark", 30), new Person("Will", 28));
people.stream().sorted((p1, p2) -> p1.age - p2.age).forEach(System.out::println);
Person{name='Paul', age=24}
Person{name='Will', age=28}
Person{name='Mark', age=30}
如果我们要编写一个函数来在Java 7中做同样的事情,它将看起来像这样:
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.age - o2.age;
}
});
for (Person person : people) {
System.out.println(person);
}
Java 8减少了我们必须编写的代码量,尽管它比我们在Ruby中所能做的还要复杂:
> people = [ {:name => "Paul", :age => 24}, {:name => "Mark", :age => 30}, {:name => "Will", :age => 28}]
> people.sort_by { |p| p[:age] }
=> [{:name=>"Paul", :age=>24}, {:name=>"Will", :age=>28}, {:name=>"Mark", :age=>30}]
几页后,Venkat展示了如何使用Comparator#comparing函数来接近这一点:
Function<Person, Integer> byAge = p -> p.age ;
people.stream().sorted(comparing(byAge)).forEach(System.out::println);
我以为可以通过内联这样的'byAge'lambda来简化此过程:
people.stream().sorted(comparing(p -> p.age)).forEach(System.out::println);
尽管IntelliJ 13.0提示存在“ 循环推断 ”问题,但这似乎可以正确编译并运行。 如果我们像下面这样显式地转换lambda,则IntelliJ很高兴:
people.stream().sorted(comparing((Function<Person, Integer>) p -> p.age)).forEach(System.out::println);
如果我们在lambda中显式键入“ p”,IntelliJ似乎也很高兴,所以我认为我暂时会这样做:
people.stream().sorted(comparing((Person p) -> p.age)).forEach(System.out::println);
翻译自: https://www.javacodegeeks.com/2014/02/java-8-sorting-values-in-collections.html
java集合根据值排序