您好,登录后才能下订单哦!
本篇内容主要讲解“怎么解决Java8 stream操作toMap的key重复问题”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么解决Java8 stream操作toMap的key重复问题”吧!
准备以下User对象集合 ,构造方法User(Long Id, String username)
List<User> userList = new ArrayList<>(); userList.add(new User(1L, "aaa")); userList.add(new User(2L, "bbb")); userList.add(new User(3L, "ccc")); userList.add(new User(2L, "ddd")); userList.add(new User(3L, "eee"));
当进行普通toMap操作时
Map<Long, String> map = userList.stream() .collect(Collectors.toMap(User::getId, User::getUsername);
就会报错,说明处理到已存在的key,其对应value为bbb
java.lang.IllegalStateException: Duplicate key bbb at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133) at java.util.HashMap.merge(HashMap.java:1253) at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320) at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169) at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
解决方式就在Java8提供的Collectors.toMap() 方法中,其第三个参数就是当出现 duplicate key的时候的处理方案
方案一: 出现重复时,取前面value的值,或者取后面放入的value值,则覆盖先前的value值
Map<Long, String> map = userList.stream() .collect(Collectors.toMap(User::getId, User::getUsername, (v1, v2) -> v1));
Map<Long, String> map = userList.stream() .collect(Collectors.toMap(User::getId, User::getUsername, (v1, v2) -> v2));
方案二: Map的value可以储存一个list,把重复key的值放入list,再存到value中
userList.stream().collect(Collectors.toMap(User::getId, e -> Lists.newArrayList(e.getUsername()), (List<String> oldList, List<String> newList) -> { oldList.addAll(newList); return oldList; }));
到此,相信大家对“怎么解决Java8 stream操作toMap的key重复问题”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。