Java 8提供了不同的实用程序api方法来帮助我们更好地对流进行排序。
如果您的列表是整数(或Double,Long,String等)的列表,则可以使用Java提供的默认比较器对列表进行排序。
List<Integer> integerList = Arrays.asList(1, 4, 3, 4, 5);
动态创建比较器:
integerList.stream().sorted((i1, i2) -> i1.compareTo(i2)).forEach(System.out::println);
使用Java 8提供的默认比较器,当没有参数传递给sorted()时:
integerList.stream().sorted().forEach(System.out::println); //Natural order
如果要对相同的列表进行反向排序:
integerList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); // Reverse Order
如果您的列表是用户定义对象的列表,则:
List<Person> personList = Arrays.asList(new Person(1000, "First", 25, 30000),
new Person(2000, "Second", 30, 45000),
new Person(3000, "Third", 35, 25000));
动态创建比较器:
personList.stream().sorted((p1, p2) -> ((Long)p1.getPersonId()).compareTo(p2.getPersonId()))
.forEach(person -> System.out.println(person.getName()));
使用Comparator.comparingLong()方法(我们也具有compareingDouble()和compareingInt()方法):
personList.stream().sorted(Comparator.comparingLong(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));
使用Comparator.comparing()方法(基于提供的getter方法进行比较的通用方法):
personList.stream().sorted(Comparator.comparing(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));
我们也可以使用thenComparing()方法进行链接:
personList.stream().sorted(Comparator.comparing(Person::getPersonId).thenComparing(Person::getAge)).forEach(person -> System.out.println(person.getName())); //Sorting by person id and then by age.
人类
public class Person {
private long personId;
private String name;
private int age;
private double salary;
public long getPersonId() {
return personId;
}
public void setPersonId(long personId) {
this.personId = personId;
}
public Person(long personId, String name, int age, double salary) {
this.personId = personId;
this.name = name;
this.age = age;
this.salary = salary;
}
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;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
list.sort(Comparator.comparing(o -> o.getItem().getValue()));
对我来说是新的。大!