List<String> strings = Arrays.asList("3","55","3");
Map<String,Integer> map = strings
.stream()
.collect(Collectors.toMap(s ->s, s -> s.length()));
返回java.lang.IllegalStateException: Duplicate key 1
我预计会出现重复的键3
List<String> strings = Arrays.asList("3","55","3");
Map<String,Integer> map = strings
.stream()
.collect(Collectors.toMap(s ->s, s -> s.length()));
返回java.lang.IllegalStateException: Duplicate key 1
我预计会出现重复的键3
这个问题在Java 9中已经得到修复。现在错误信息是正确的:
java.lang.IllegalStateException: Duplicate key 3 (attempted merging values 1 and 1)
https://bugs.openjdk.java.net/browse/JDK-8040892
它本身是其他帖子的副本。
是的,这是一个bug,但还有另一种将其转换为映射的方法,那就是使用身份函数:
List<String> strings = Arrays.asList("3","55","3");
Map<String, List<String>> map = strings.stream()
.collect(Collectors.toMap(Function.identity(), Arrays::asList));
通过这样做,您将获得正确的错误信息,即
java.lang.IllegalStateException: Duplicate key [3]
对于具有唯一值的数组
List<String> strings = Arrays.asList("3","55","4");
结果将会是
{55=[55], 3=[3], 4=[4]}
HashMap$Node
的value
而不是它的key
... - MenaCollectors.toMap(s ->s, s ->4)
,则会收到java.lang.IllegalStateException: Duplicate key 4
的错误提示,因此似乎实际上是在抱怨值重复。 - Bentaye