Search code examples
javadictionarylambdajava-streamcollectors

How to convert a List<String> to Map<String, Long> using Lambda, where the key is the String and the value is a count of the number of vowels?


Given:

List<String> myStrings = Arrays.asList("broom", "monsoon");

Return:

Map<String, Long> stringToNumberOfVowels = Map.of("broom", 2, "monsoon", 3);

This is what i've tried:

Map<String, Long> vowelsMap = Stream.of("broom").flatMapToInt(String::chars).filter("aeiou".indexOf(c) >= 0).mapToObj(c -> "aeiou".indexOf(c)>=0 ? "broom" : "").collect(Collectors.groupingBy(Function.indenty(), Collectors.counting()));

for(Map.Entry<String, Long> a : vowelsMap.entrySet()) { System.out.println(a.getKey() + "==>"); System.out.println(a.getValue()); }

My Output (which only works with 1 string being passed in the stream):

broom ==> 2

Desired Output:

broom ==> 2

monsoon ==> 3


Solution

  • Your logic is a little bit complicted, a simple way is to use stream collect with Collectors::toMap like this:

    Map<String, Long> vowelsMap = myStrings.stream()
            .collect(Collectors.toMap(Function.identity(), 
                    str -> str.chars().filter(c -> "aeiou".indexOf(c) >= 0).count()));