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!

1 Answer 1

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)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.