I'd like to convert a Map <String, Integer> from List<String> in 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'd like to to create a Map, where the key is the string of the list, and the value is Integer (a zero).
My goal is, to counting the elements of String list (later in my code).
I know it is easy to convert it, in the "old" way;
Map<String,Integer> namesMap = new HasMap<>();
for(String str: names) {
map1.put(str, 0);
}
but I'm wondering there is a Java 8 solution as well.
0toname -> 0:Map<String, Integer> namesMap = names.stream().collect(Collectors.toMap(name -> name, name -> 0));but this will fail if you have duplicates. If you want to count occurrences, do it right in the first place:Map<String, Long> namesMap = names.stream().collect(Collectors.groupingBy(name -> name, Collectors.counting()));Instead ofname -> name, you can also useFunction.identity().