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表结构主要有:

java将一个集合的对象merge到另一个集合 java集合转map_List

 

 T_FUNDCONTACTRELA表结构主要有:

java将一个集合的对象merge到另一个集合 java集合转map_User_02

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

// 首先第一步就是从产品联系人关联关系表根据前端界面传递的产品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);

                });

            }

        }