Java8中stream()操作toMap()时Duplicate key问题解决

问题描述:

最近使用Java8中Steam()流进行tomap转换编程时,遇到以下错误

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)

原因分析:

正如错误提示中所说的那样,tomap时遇到了重复键的问题,这里举个例子并记录一下解决方法。

准备以下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);

解决方案:

解决方式就在Java8提供的Collectors.toMap() 方法中,其第三个参数就是当出现 duplicate key的时候的处理方案

方案一: 出现重复时,取前面value的值,或者取后面放入的value值,则覆盖先前的value值

// 取后面的值,舍弃前面的值
Map<Long, String> map = userList.stream()
            .collect(Collectors.toMap(User::getId, User::getUsername, (v1, v2) -> v2));

// 取前面的值,舍弃后面的值
Map<Long, String> map = userList.stream()
            .collect(Collectors.toMap(User::getId, User::getUsername, (v1, v2) -> v1));

方案二: Map的value可以储存一个list,把重复key的值放入list,再存到value中


userList.stream().collect(Collectors.toMap(User::getId,
                e -> Arrays.asList(e.getUsername()),
                (List<String> oldList, List<String> newList) -> {
                    oldList.addAll(newList);
                    return oldList;
                }));

你可能感兴趣的:(java,stream)