Lamdba表达式转Map五种最实用方式

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));

完结各位有什么不足提出来

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值