Skip to content
Advertisement

how to get size of list value of map by streams in java

I’m trying to group a list of strings by the length. and then I want to get count of each group. and I did the first one and I can’t do the next. how can I fix my code with streams?

Stream.of(Stream.of("Brad","Jack","Leonardo","Alexander","Juliet","William","Audrey")
                .collect(Collectors.groupingBy(String::length)))
                .forEach(System.out::print);

output: {4=[Brad, Jack], 6=[Juliet, Audrey], 7=[William], 8=[Leonardo], 9=[Alexander]}

the next thing that I want to get is count of each group. How can I do that?

Advertisement

Answer

You can chain Collectors.counting():

Map<Integer,Long> counts = 
   Stream.of("Brad","Jack","Leonardo","Alexander","Juliet","William","Audrey")
         .collect(Collectors.groupingBy(String::length,
                                        Collectors.counting()));

This will produce the following Map:

{4=2, 6=2, 7=1, 8=1, 9=1}
Advertisement