java8新特性

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

实际项目中的例子:

1// 获取机构信息List<InstInfo> instInfoList = instInfoAtom.getInstInfo(instInfo);Map<String, InstInfo> instInfoMap = instInfoList.stream().collect(Collectors.toMap(InstInfo::getInstId, Function.identity())); 2 3InstInfo
点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

javabean转jsonObject

工程场景:需要将一个javaBean转换成jsonObject对象。假设UserusernewUser();有三个属性,name、age、sex,我们对其设值user.setName("张三");user.setAget("32");user.setSex(null);现需要转换,我采用的方法是:JS

java 数据结构(十二):Collections工具类的使用

Collections工具类1.作用:操作Collection和Map的工具类2.常用方法:reverse(List):反转List中元素的顺序shuffle(List):对List集合元素进行随机排序sort(List):根据元素的自然顺序对指定List集合元素升序排序sort(List,Comparator)

1.利用BeanMap进行对象与Map的相互转换

javabean与map的转换有很多种方式,比如:1、通过ObjectMapper先将bean转换为json,再将json转换为map,但是这种方法比较绕,且效率很低,经测试,循环转换10000个bean,就需要12秒!!!不推荐使用2、通过java反射,获取bean类的属性和值,再转换到map对应的键值对中,这种方法次之,但稍微有点麻烦3、通过

Spring Boot Jackson命名策略

在SpringBoot的Jackson中我们可以使用@JsonProperty对Java属性转Json字符串的key进行指定。那么,当批量处理统一类型的格式时,@JsonProperty就显得比较麻烦了。publicclassLoginUser{@JsonProperty("user_name")priv

JAVA常用编程代码块

转Map时要考虑Map的key是否重复List<Entity转为Map<keyField,valueField将一个List实体集合转换为以Entity某一个字段为key,另一字段为value映射的Map/