Java 8 List into Map

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

    Most of the answers listed, miss a case when the list has duplicate items. In that case there answer will throw IllegalStateException. Refer the below code to handle list duplicates as well:

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

提交回复
热议问题