0

I have a Stream<String> of a file, now i want to combine equal words into a Map<String, Integer> which counts, how often the word is in the Stream<String>.

I know that I have to use collect(Collectors.groupingBy(..)), but i do not know how to use it.

It would be very nice, if there is somebody who can provide some hints how to solve this problem!

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334

1 Answers1

1

It's quite easy to create Map<String, Long> using the Collectors.counting() as downstream collector:

Stream<String> s = Stream.of("aaa", "bb", "cc", "aaa", "dd");

Map<String, Long> map = s.collect(Collectors.groupingBy(
        Function.identity(), Collectors.counting()));

If you don't like Long type, you can count to Integer this way:

Map<String, Integer> mapInt = s.collect(Collectors.groupingBy(
        Function.identity(),
        Collectors.reducing(0, str -> 1, Integer::sum)));
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334