javalambdajava-stream

Counting occurences of chars in string with stream


I'm trying to understand a data flow of streams in Java. My task is to put occurrences of each letter in list of strings

List<String> words = Arrays.asList("Welcome", "to", "the", "java", "world");

into

Map<String, Long>

using a one-liner stream.

I know, that in the first place we can stream each word from the list, then I need to separate it into chars, then put each char as key and count its occurrence as value and in the end return the whole map.

It is so complicated to understand. Could someone explain to me how to do it?


Solution

  • It could be done as Willis pointed out using the flatMap and groupingBy collector. But, the expected output type should be Map<Character, Long> fo that as in:

    Map<Character, Long> charFrequency = words.stream() //Stream<String>
            .flatMap(a -> a.chars().mapToObj(c -> (char) c)) // Stream<Character>
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));