Java 8 List into Map

前端 未结 22 2747
半阙折子戏
半阙折子戏 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:23

    It's possible to use streams to do this. To remove the need to explicitly use Collectors, it's possible to import toMap statically (as recommended by Effective Java, third edition).

    import static java.util.stream.Collectors.toMap;
    
    private static Map nameMap(List choices) {
        return choices.stream().collect(toMap(Choice::getName, it -> it));
    }
    

提交回复
热议问题