Java 8 toMap IllegalStateException 重复键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28773685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 toMap IllegalStateException Duplicate Key
提问by pramodh
I have a file which contains data in the following format
我有一个包含以下格式数据的文件
1
2
3
I want to load this to map as {(1->1), (2->1), (3->1)}
我想加载这个映射为 {(1->1), (2->1), (3->1)}
This is the Java 8 code,
这是Java 8代码,
Map<Integer, Integer> map1 = Files.lines(Paths.get(inputFile))
.map(line -> line.trim())
.map(Integer::valueOf)
.collect(Collectors.toMap(x -> x, x -> 1));
I am getting the following error
我收到以下错误
Exception in thread "main" java.lang.IllegalStateException: Duplicate key 1
How do I fix this error?
我该如何解决这个错误?
采纳答案by pramodh
The code will run if there are no duplicates in the file.
如果文件中没有重复项,代码将运行。
Map<Integer, Integer> map1 = Files.lines(Paths.get(inputFile))
.map(String::trim)
.map(Integer::valueOf)
.collect(Collectors.toMap(x -> x, x -> 1));
If there are duplicates use the following code to get the total number of occurrences in the file for that key.
如果存在重复项,请使用以下代码获取该键在文件中出现的总次数。
Map<Integer, Long> map1 = Files.lines(Paths.get(inputFile))
.map(String::trim)
.map(Integer::valueOf)
.collect(Collectors.groupingBy(x -> x, Collectors.counting());
回答by KeyMaker00
The pramodh's answer is good if you want to map your value to 1. But in case you don't want to always map to a constant, the use of the "merge-function" might help:
如果您想将值映射到 1,则 pramodh 的答案很好。但是,如果您不想始终映射到常量,则使用“合并函数”可能会有所帮助:
Map<Integer, Integer> map1 = Files.lines(Paths.get(inputFile))
.map(line::trim())
.map(Integer::valueOf)
.collect(Collectors.toMap(x -> x, x -> 1, (x1, x2) -> x1));
The above code is almost the same as posted in the question. But if it encounters a duplicate key
, instead of throwing an exception, it will solve it by applying the merge function, by taking the first value.
上面的代码与问题中发布的代码几乎相同。但是如果遇到 a duplicate key
,它不会抛出异常,而是通过应用合并函数,取第一个值来解决它。