工作经常会遇到list转为 map 的情况,可能我们只需要某个字段的值转为map集合,在jdk8以前,我们更多地可能会用 for循环 的方式,然后put到map中去,有了jdk8之后,我们可以使用简单的一句话,就可以搞定
关键语句:Map<String,Integer> map = userList.stream().collect(Collectors.toMap(UserBean::getUserName, UserBean::getAge,(key1,key2) ->key2));解释
key值重复报错信息:
Exception in thread “main” java.lang.IllegalStateException: Duplicate key 21
at java.util.stream.Collectors.lambda$throwingMerger$0(Unknown Source)
at java.util.HashMap.merge(Unknown Source)
at java.util.stream.Collectors.lambda$toMap$58(Unknown Source)
at java.util.stream.ReduceOps$3ReducingSink.accept(Unknown Source)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline. copy Into(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.collect(Unknown Source)
at test.LamdaTest.abc(LamdaTest.java:32)
at test.LamdaTest.main(LamdaTest.java:12)
我们也可以指定返回的Map为哪种类型:
Map<String,Integer> map = userList.stream().collect(Collectors.toMap(UserBean::getUserName, UserBean::getAge,(key1,key2) ->key2, LinkedHashMap ::new ));
要注意的坑:value的值不能为null,否则会报错
I do like the manner in which you have presented this difficulty and it really does provide me a lot of fodder for thought. Nonetheless, because of what I have personally seen, I just hope as the actual commentary stack on that people today keep on issue and in no way embark on a tirade involving the news of the day. All the same, thank you for this fantastic piece and although I do not necessarily go along with the idea in totality, I regard the viewpoint.