Java 8 toMap IllegalStateException Duplicate Key

后端 未结 2 444
南旧
南旧 2020-12-08 18:21

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)}

2条回答
  •  青春惊慌失措
    2020-12-08 19:09

    The code will run if there are no duplicates in the file.

    Map 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 map1 = Files.lines(Paths.get(inputFile))
                .map(String::trim)
                .map(Integer::valueOf)
                .collect(Collectors.groupingBy(x -> x, Collectors.counting());
    

提交回复
热议问题