Java reduce a collection of string to a map of occurence

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Java reduce a collection of string to a map of occurence



Consider the a list as id1_f, id2_d, id3_f, id1_g, how can I use stream to get a reduced map in format of <String, Integer>of statistics like:


id1_f, id2_d, id3_f, id1_g


<String, Integer>


id1 2
id2 1
id3 1



Note: the key is part before _. Is reduce function can help here?


_


reduce




1 Answer
1



This will get the job done:


Map<String, Long> map = Stream.of("id1_f", "id2_d", "id3_f", "id1_g")
.collect(
Collectors.groupingBy(v -> v.substring(0, v.indexOf("_")),
Collectors.counting())
);






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Jenkinsfile syntax highlighting in Java project using Intellij Idea

In Windows 7 Git Bash, is there a way to explore the directory at the current location?

Web Scraping Python Beautiful Soup