0
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?

Angela
  • 11
  • 2
  • No. But you can write your own collector with your own Map. – f1sh Apr 03 '20 at 22:45
  • 6
    That looks like [XY problem](https://meta.stackexchange.com/q/66377). I am guessing you probably wanted to know how to [Group by counting in Java 8 stream API](https://stackoverflow.com/q/25441088) – Pshemo Apr 03 '20 at 22:49

1 Answers1

3

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 ;)