Java 8 toMap IllegalStateException Duplicate Key

后端 未结 2 440
南旧
南旧 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 18:51

    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:

    Map 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.

提交回复
热议问题