Collectors.toMap IllegalStateException:没有重复时重复键

时间:2016-03-17 18:33:29

标签: java exception java-stream

我一直在遇到这个错误而且我无法理解它,因为它抱怨只出现一次的值。

Exception in thread "main" java.lang.IllegalStateException: Duplicate key wp-admin/admin-ajax.php#13236
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1245)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
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)
at <my code>

这是原始代码:

reader.lines().filter(line -> line.startsWith(TAG_MAPPED_NODE)).map(line -> {
    final String[] splitted = line.split(" ");
    if (splitted.length != 3)
        throw new IllegalStateException("Unexpected line: " + line);
    return splitted;(splitted[1],splitted[2]);
}).collect(Collectors.toMap(t -> t[1], t -> t[2]));

然而,它抱怨的价值只存在一次。验证码:

List<String> usefulLines =
    reader.lines().filter(line -> line.startsWith(TAG_MAPPED_NODE)).collect(Collectors.toList());
List<String> trouble =
    usefulLines.stream().filter(line -> line.contains("wp-admin/admin-ajax.php#13236")).collect(Collectors.toList());
System.out.println("Trouble size: " + trouble.size());
return usefulLines.stream().map(line -> {
    final String[] splitted = line.split(" ");
    if (splitted.length != 3)
        throw new IllegalStateException("Unexpected line: " + line);
    return splitted;
}).collect(Collectors.toMap(t -> t[1], t -> t[2]));

输出为:Trouble size: 1

因此,只有一个条目具有此值(并且,我必须添加,我将其存储在Map的Value侧, not Key)

系统配置:

  • Java版本:openjdk版本“1.8.0_72”
  • IDE:IntelliJ IDEA 2016.1
  • 操作系统:Fedora 22 64位

那么我在世界上如何得到这个例外?这看起来像是一个JDK错误 - 任何人看到我做错了什么?

2 个答案:

答案 0 :(得分:1)

我的解决方案是用番石榴ImmutableMap.toImmutableMap()替换bug Collectors.toMap()。耶!

答案 1 :(得分:0)

正如对该问题的评论所指出的那样,此处的混乱是由于Java 8(JDK-8040892l)中的一个错误所致,该错误中该值作为重复项而不是键被打印出来。因此,实际上有一个重复的键,但这不是异常消息中显示的值。在这种情况下,任何映射到“ wp-admin / admin-ajax.php#13236”的密钥都是重复的密钥。