Java8 Stream常用方法
1:过滤
list.stream().filter(p-> p.getAge() > 20).collect(Collectors.toList());
2:去重
使用distinct去重时对象需要重写的hashCode()和equals(),先比较hashCode
list.stream().distinct().collect(Collectors.toList());
//TreeSet 去重
list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getSex))), ArrayList::new));
3:排序
sorted() 默认使用自然序排序, 其中的元素必须实现Comparable(可自写) 接口
list.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
4:提取对象 List 中的某一字段生成新的 List
list.stream().map(Person::getName).collect(Collectors.toList());
5: 根据的某一字段生成 Map
第三个参数指key值重复时,保留p1旧值或p2新值
//Function.identity() 可以用p -> p;
list.stream().collect(Collectors.toMap(Person::getName, Function.identity(), (p1, p2) -> p2));
6:分组
可以多级分组
Map<String, List<Person>> listMap = list.stream().collect(Collectors.groupingBy(Person::getName));
7:分区
Map<Boolean, List<Person>> booleanListMap = list.stream()
.collect(Collectors.partitioningBy(p -> p.getAge() > 20));