collect(Collectors.toMap(String::toString, str -> {map.get(str)+1})
I want to maintain counts of strings in a map. Is there anyway to access the map the Collector is collecting into?
collect(Collectors.toMap(String::toString, str -> {map.get(str)+1})
I want to maintain counts of strings in a map. Is there anyway to access the map the Collector is collecting into?
You can try to make something like this :
List<String> list1 = Arrays.asList("red", "blue", "green");
Map<String, Integer> map1 = list1.stream().collect(Collectors.toMap(String::toString, t -> t.length()));
But if you have a duplicate value in your list you should merge them :
List<String> list2 = Arrays.asList("red", "red", "blue", "green");
Map<String, Integer> map2 = list2.stream()
.collect(Collectors.toMap(String::toString, t -> t.length(), (line1, line2) -> line1));
And, if you want to make your code more efficient you can use a parallel stream with concurrent map but you have to ensure that you don't have a null value (for more information about the concurrent map you refer to the official documentation)
List<String> list3 = Arrays.asList("red", "red", "blue", "green", null);
Map<String, Integer> map3 = list3.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toConcurrentMap(String::toString, t -> t.length(), (line1, line2) -> line1));
I hope this is useful to you ;)