(一)多条件过滤-filter
studentList.add(new Student("Alice", "10", 15));
studentList.add(new Student("Bob", "10", 16));
studentList.add(new Student("Charlie", "11", 14));
studentList.add(new Student("David", "11", 17));
studentList.add(new Student("Eve", "12", 16));
//多条件过滤
List<Student> filter = studentList.stream().
filter(student -> "Alice".equals(student.getName()) && "10".equals(student.getClassName())).collect(Collectors.toList());
(二)去重-distinct-根据某个属性去重
studentList.add(new Student("Alice", "10", 15));
studentList.add(new Student("Bob", "10", 16));
studentList.add(new Student("Charlie", "11", 14));
studentList.add(new Student("David", "11", 17));
studentList.add(new Student("Eve", "12", 16));
//根据班级className去重
Set<String> distinctSet = new HashSet<>();
//这里用了set集合的add()方法,该方法当集合中已存在这个元素会返回false,如果不存在则返回true,添加成功。这样即实现了对整个集合对象的去重,也能拿到某个属性去重后的集合distinctSet
List<Student> distinctList = studentList.stream().filter(student -> distinctSet.add(student.getClassName())).collect(Collectors.toList());
这里用了set集合的add()方法,该方法当集合中已存在这个元素会返回false,如果不存在则返回true,添加成功。这样即实现了对整个集合对象的去重,也能拿到某个属性去重后的集合distinctSet
(三)截取-limit
//取第一条
List<Student> limitList = studentList.stream().limit(1).collect(Collectors.toList());
(四)排序-sort
//排序sort--默认升序
List<Student> sortList = studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
//排序sort--降序要加上reversed()
List<Student> sortReversedList = studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
(五)分组排序后取每组第一条
studentList.add(new Student("Alice", "10", 15));
studentList.add(new Student("Bob", "10", 16));
studentList.add(new Student("Charlie", "11", 14));
studentList.add(new Student("David", "11", 17));
studentList.add(new Student("Eve", "12", 16));
//按className分组,再按年龄排序,然后取每组第一条--这里的排序可以用min或max代替更简便
Map<String, Student> groupByList = studentList.stream()
.collect(Collectors.groupingBy(
Student::getClassName,
Collectors.collectingAndThen(
Collectors.toList(),
list ->
list.stream().min(Comparator.comparing(Student::getAge))
.orElse(null)
)
));
这里用到了Collectors.collectingAndThen(),此方法可以在流中进行常规的收集,就是可以把你想操作的对象转成list或map或set之后,再进行流操作,例如排序或过滤,非常好用。