Lamdba表达式转Map五种方式
第一种
根据性别进行分组默认VALUE值默认为对象:Map<String, List>
Map<String, List<Person>> personByGender = persons.stream()
.collect(Collectors.groupingBy(Person::getGender));
第二种
按照年龄进行已过18岁进行分租 Map<Boolean, List>
Map<Boolean, List<Person>> personsByAge = persons.stream() .collect(Collectors.partitioningBy(p -> p.getAge() > 18));
第三种
前面介绍的partitioningBy和groupingBy返回Map的value部分都是List结构的,有时我们需要value是对象的一个属性,比如我们想构造一个uuid到name的映射,以方便通过uuid快速获取人员的名字,同时解决key冲突问题
返回 Map<String, String>
Map<String, String> uuidNameMap = persons.stream()
.collect(Collectors.toMap(Person::getUuid, Person::getName,(k2,k1)->k1));
第四种
返回<Person::getName, Person>
Map<String, Personal> uuidNameMap = persons.stream()
.collect(Collectors.toMap(Person::getUuid, v -> v,(p1, p2) -> p1));
第五种
使用TreeSet去重后转List实现 返回 List
List<Product2>=beans.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()-> new TreeSet<>(Comparator.comparing(Product2::getXxx))),ArrayList::new));
完结各位有什么不足提出来