Java8集合内对象按照多条件排序及取前几条
1,实例代码,注意(如果排序属性为字符串,必须要给其转换为数字类型,而后排序,否则排序不准)
import lombok.Data;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
Person p1 = new Person("zhangsan", 11, "180");
Person p2 = new Person("lisi", 10, "190");
Person p3 = new Person("wangwu", 10, "160");
Person p5 = new Person("xiaozhang", 10, "170");
Person p4 = new Person("zhouliu", 9, "170");
List<Person> people = Arrays.asList(p1, p2, p3, p4,p5);
List<Person> ageSortList = people.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
ageSortList.stream().sorted(Comparator.comparing(Person::getAge)
.thenComparing(Person::getTall, Comparator.reverseOrder()))
.forEach(System.out::println);
}
@Data
static class Person {
private String name;
private Integer age;
private String tall;
public Person(String name, Integer age, String tall) {
this.name = name;
this.age = age;
this.tall = tall;
}
}
}
参考文章
Comparator 使用详解
https://www.cnblogs.com/kuanglongblogs/p/11230250.html