Java reduce a collection of string to a map of occurence

Multi tool use
Multi tool use
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.

MDKV2ss2h,1HqWT43eJKfv2ng vR,2JNXrC8
49,GRAXx6m8DALOoebKT21 La4z5bawbUV,mmN9AYN tN54 5 WUSdXh 5Rj

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

415 Unsupported Media Type while sending json file over REST Template