java8 list 转 map

2021/6/1 14:23:45

本文主要是介绍java8 list 转 map,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

List<NodeRoleRelationListVo> nodeRoleList = nodeRoleRelationFeign.selectList(new NodeRoleRelationReqVo()).getData();
//Stream将List转换为Map,使用Collectors.toMap方法进行转换


//1、指定key-value,value是对象中的某个属性值。
Map<String,String> nodeRoleMap = nodeRoleList.stream().collect(Collectors.toMap(NodeRoleRelationListVo::getNodeCode,NodeRoleRelationListVo::getRoleCode));


//2、指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式
nodeRoleList.stream().collect(Collectors.toMap(NodeRoleRelationListVo::getNodeCode,NodeRoleRelationListVo->NodeRoleRelationListVo));


//3、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身
nodeRoleList.stream().collect(Collectors.toMap(NodeRoleRelationListVo::getNodeCode, Function.identity()));


//4、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key。
nodeRoleList.stream().collect(Collectors.toMap(NodeRoleRelationListVo::getNodeCode, Function.identity(),(key1,key2)->key2));


                   

这篇关于java8 list 转 map的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程