我有一个包含以下格式数据的文件
1
2
3我想将其作为{(1->1), (2->1), (3->1)}加载到地图中
这是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));我收到以下错误
Exception in thread "main" java.lang.IllegalStateException: Duplicate key 1如何修复此错误?
发布于 2015-02-28 06:10:11
如果文件中没有重复项,代码将会运行。
Map<Integer, Integer> map1 = Files.lines(Paths.get(inputFile))
.map(String::trim)
.map(Integer::valueOf)
.collect(Collectors.toMap(x -> x, x -> 1));如果存在重复项,则使用以下代码获取该键在文件中出现的总次数。
Map<Integer, Long> map1 = Files.lines(Paths.get(inputFile))
.map(String::trim)
.map(Integer::valueOf)
.collect(Collectors.groupingBy(x -> x, Collectors.counting());发布于 2018-05-24 16:49:06
如果你想将你的值映射到1,那么pramodh的答案是很好的。但是如果你不想总是映射到一个常量,使用"merge-function“可能会有所帮助:
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));上面的代码与问题中发布的代码几乎相同。但是如果它遇到了duplicate key,它不会抛出异常,而是通过应用函数来通过第一个值进行合并来解决它。
https://stackoverflow.com/questions/28773685
复制相似问题