Java List to Map convertion

后端 未结 2 1593
情话喂你
情话喂你 2021-01-12 14:39

I\'d like to convert a Map from List in java 8 something like this:

Map

        
相关标签:
2条回答
  • 2021-01-12 14:48

    As already noted, the parameters to Collectors.toMap have to be functions, so you have to change 0 to name -> 0 (you can use any other parameter name instead of name).

    Note, however, that this will fail if there are duplicates in names, as that will result in duplicate keys in the resulting map. To fix this, you could pipe the stream through Stream.distinct first:

    Map<String, Integer> namesMap = names.stream().distinct()
                                         .collect(Collectors.toMap(s -> s, s -> 0));
    

    Or don't initialize those defaults at all, and use getOrDefault or computeIfAbsent instead:

    int x = namesMap.getOrDefault(someName, 0);
    int y = namesMap.computeIfAbsent(someName, s -> 0);
    

    Or, if you want to get the counts of the names, you can just use Collectors.groupingBy and Collectors.counting:

    Map<String, Long> counts = names.stream().collect(
            Collectors.groupingBy(s -> s, Collectors.counting()));
    
    0 讨论(0)
  • 2021-01-12 15:03

    the toMap collector receives two mappers - one for the key and one for the value. The key mapper could just return the value from the list (i.e., either name -> name like you currently have, or just use the builtin Function.Identity). The value mapper should just return the hard-coded value of 0 for any key:

    namesMap = 
        names.stream().collect(Collectors.toMap(Function.identity(), name -> 0));
    
    0 讨论(0)
提交回复
热议问题