Java 8 List into Map

前端 未结 22 2481
半阙折子戏
半阙折子戏 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:11
    Map<String, Set<String>> collect = Arrays.asList(Locale.getAvailableLocales()).stream().collect(Collectors
                    .toMap(l -> l.getDisplayCountry(), l -> Collections.singleton(l.getDisplayLanguage())));
    
    0 讨论(0)
  • 2020-11-22 04:12

    Another possibility only present in comments yet:

    Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(c -> c.getName(), c -> c)));
    

    Useful if you want to use a parameter of a sub-object as Key:

    Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(c -> c.getUser().getName(), c -> c)));
    
    0 讨论(0)
  • 2020-11-22 04:13

    I use this syntax

    Map<Integer, List<Choice>> choiceMap = 
    choices.stream().collect(Collectors.groupingBy(choice -> choice.getName()));
    
    0 讨论(0)
  • 2020-11-22 04:15

    As an alternative to guava one can use kotlin-stdlib

    private Map<String, Choice> nameMap(List<Choice> choices) {
        return CollectionsKt.associateBy(choices, Choice::getName);
    }
    
    0 讨论(0)
  • 2020-11-22 04:17

    Here's another one in case you don't want to use Collectors.toMap()

    Map<String, Choice> result =
       choices.stream().collect(HashMap<String, Choice>::new, 
                               (m, c) -> m.put(c.getName(), c),
                               (m, u) -> {});
    
    0 讨论(0)
  • 2020-11-22 04:20

    If your key is NOT guaranteed to be unique for all elements in the list, you should convert it to a Map<String, List<Choice>> instead of a Map<String, Choice>

    Map<String, List<Choice>> result =
     choices.stream().collect(Collectors.groupingBy(Choice::getName));
    
    0 讨论(0)
提交回复
热议问题