javajava-stream

Convert List of strings to HashMap of string lengths using Stream


I have this List:

List<String> g = Arrays.asList("aa","ab","aaa","aaaa");

How can I print the output using Java streams?

{2=[2]}  //two-letter word = 2
{3=[1]}  //three-letter word = 1
{4=[1]}  //four-letter word = 1

I've written the following:

g.stream().collect(Collectors.groupingBy(String::length))
    .forEach((k,v) -> System.out.println(String.format(k,v)));

But this prints the list of matching values, rather than their count:

{2=[aa, ab]}
{3=[aaa]}
{4=[aaaa]}

Solution

  • List<String> g= Arrays.asList("aa","ab","aaa","aaaa");
            g.stream()
                    .collect(Collectors.groupingBy(String::length))
                    .forEach((k,v) -> System.out.printf("{%d=[%d]}%n",k ,v.size()));
    

    Output:

    {2=[2]}
    {3=[1]}
    {4=[1]}