简体   繁体   中英

Stream<String> to Map<String, Integer>

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM