Java list <String> for conversion <String, Integer>

I would like to convert Map <String, Integer>from List<String>to java 8 something like this:

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

because I have a list of strings and I would like to create a map where the key is the list string and the value is an integer (zero).

My goal is to count the elements of a String list (later in my code).

I know that it’s easy to transform it, the old way,

Map<String,Integer> namesMap = new HasMap<>();
for(String str: names) {
  map1.put(str, 0);
}

but I am wondering if there is a solution for Java 8.

+4
source share
2 answers

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

, , names , . , Stream.distinct:

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

, getOrDefault computeIfAbsent:

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

, , Collectors.groupingBy Collectors.counting:

Map<String, Long> counts = names.stream().collect(
        Collectors.groupingBy(s -> s, Collectors.counting()));
+6

toMap - . - (.. name -> name, , Function.Identity). 0 :

namesMap = 
    names.stream().collect(Collectors.toMap(Function.identity(), name -> 0));
+5

Source: https://habr.com/ru/post/1670936/


All Articles