Java 8 toMap IllegalStateException重复键

pra*_*odh 40 java java-8

我有一个文件,其中包含以下格式的数据

1
2
3
Run Code Online (Sandbox Code Playgroud)

我想加载它来映射为 {(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));
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

Exception in thread "main" java.lang.IllegalStateException: Duplicate key 1
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个错误?

Key*_*r00 25

如果你想将你的值映射到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));
Run Code Online (Sandbox Code Playgroud)

上面的代码与问题中的帖子几乎相同.但是如果它遇到a duplicate key,而不是抛出异常,它将通过应用合并函数,通过获取第一个值来解决它.


pra*_*odh 22

如果文件中没有重复项,代码将运行.

Map<Integer, Integer> map1 = Files.lines(Paths.get(inputFile))
            .map(String::trim)
            .map(Integer::valueOf)
            .collect(Collectors.toMap(x -> x, x -> 1));
Run Code Online (Sandbox Code Playgroud)

如果存在重复项,请使用以下代码获取该项文件中出现的总次数.

Map<Integer, Long> map1 = Files.lines(Paths.get(inputFile))
            .map(String::trim)
            .map(Integer::valueOf)
            .collect(Collectors.groupingBy(x -> x, Collectors.counting());
Run Code Online (Sandbox Code Playgroud)

  • 你可以做`collect(Collectors.groupingBy(x - > x,Collectors.counting()))`这可能比`toMap()`的3-arg形式更清晰.此外,您还可以使用`String :: trim`而不是`line - > line.trim()`. (2认同)
  • 啊,`counting()`累积成一个`Long`,所以你必须将map声明改为`Map <Integer,Long>`. (2认同)
  • 旁注:`Files.lines`不会自动关闭文件 - 如果你这么做很多,你可能会遇到"打开太多文件"的错误.你可以使用try-with-resources:`try(Stream <String> lines = Files.lines(...)){lines.map(String :: trim)....}` (2认同)
  • @assylias对于将来的读者,他们在[11](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html# lines(java.nio.file.Path)):_通过关闭流来关闭文件。 (2认同)