Java reduce a collection of string to a map of occurence

Multi tool use


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.