​java8新特性--Stream将List转为Map汇总​

Stream将List转换为Map,使用Collectors.toMap方法进行转换

背景:User类,类中分别有id,name,age三个属性。List集合,userList,存储User对象

1、指定key-value,value是对象中的某个属性值

 Map<Integer,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));

2、指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式

Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));

3、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身

 Map<Integer,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

4、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key

 Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));

实际项目中的例子:

T_CONTACTOR表结构主要有:

 T_FUNDCONTACTRELA表结构主要有:

 

业务如下:首先有一张产品跟联系人关联关系表和一张联系人表,当我在界面新增一个联系人数据时,数据进入的是T_CONTACTOR表,如果需要给该联系人绑定产品,则加一条数据进入T_FUNDCONTACTRELA产品联系人关联关系表,在关联关系表的主要有CONTACTOR_ID这个字段绑定关系。那么下面我在页面根据产品ID为条件查询出所有跟该产品绑定了关联关系的联系人(主键是CONTACTOR_ID),然后在界面上想要展示的是这个产品下的联系人的详细信息。那么代码实现(因为项目因为,使用单表查询然后在使用java去匹配,更快捷的方式当然是使用两个表联合查询)做法可以有如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// 首先第一步就是从产品联系人关联关系表根据前端界面传递的产品ID查询出绑定了该产品下的所有联系人

List<FundContRela> fundContRelaList = fundContRelaAtom.getFundContRela(fundContRela);

        if (CollectionUtils.isNotEmpty(fundContRelaList)) {

            // 第二步就是从联系人表查询出所有联系人

            List<ContactorInfoInputDTO> contactorListDTOList = getContactorList(fundContactorListDTO);

            // 查询的联系人信息不能为空

            if (CollectionUtils.isNotEmpty(contactorListDTOList)) {

// 将list集合转化成Map<联系人主键ID, 联系人对象>这种格式

                Map<String, ContactorInfoInputDTO> contactorListDTOMap

= contactorListDTOList.stream().collect(Collectors

.toMap(ContactorInfoInputDTO::getContactorId, Function.identity()));

                //3、遍历关系集合,匹配联系人

                fundContRelaList.forEach(v -> {

                    FundContactorListDTO target = new FundContactorListDTO();

                    BeanUtils.copyProperties(v, target);

// contactorListDTOMap.get(v.getContactorId()) != null 判断作用就是为了过滤出存在产品联系人关联关系表根据产品ID查询出来的集合fundContRelaList 范围内的联系人

                    if (null != contactorListDTOMap && null 

!= contactorListDTOMap.get(v.getContactorId())) {

                        ContactorInfoInputDTO source = contactorListDTOMap.get(v.getContactorId());

                        BeanUtils.copyProperties(source, target);

                    }

                    out.add(target);

                });

            }

        }

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值