Java 8 List into Map

前端 未结 22 2480
半阙折子戏
半阙折子戏 2020-11-22 03:38

I want to translate a List of objects into a Map using Java 8\'s streams and lambdas.

This is how I would write it in Java 7 and below.

private Map&l         


        
22条回答
  •  死守一世寂寞
    2020-11-22 04:24

    If every new value for the same key name has to be overridden:

    public Map < String, Choice > convertListToMap(List < Choice > choices) {
        return choices.stream()
            .collect(Collectors.toMap(Choice::getName,
                Function.identity(),
                (oldValue, newValue) - > newValue));
    }
    

    If all choices have to be grouped in a list for a name:

    public Map < String, Choice > convertListToMap(List < Choice > choices) {
        return choices.stream().collect(Collectors.groupingBy(Choice::getName));
    }
    

提交回复
热议问题