Search code examples
javalistjava-8hashmapcollectors

Map to List after filtering on Map's key using Java8 stream


I have a Map<String, List<String>>. I want to transform this map to a List after filtering on the map's key.

Example:

Map<String, List<String>> words = new HashMap<>();
List<String> aList = new ArrayList<>();
aList.add("Apple");
aList.add("Abacus");

List<String> bList = new ArrayList<>();
bList.add("Bus");
bList.add("Blue");
words.put("A", aList);
words.put("B", bList);

Given a key, say, "B"

Expected Output: ["Bus", "Blue"]

This is what I am trying:

 List<String> wordsForGivenAlphabet = words.entrySet().stream()
    .filter(x-> x.getKey().equalsIgnoreCase(inputAlphabet))
    .map(x->x.getValue())
    .collect(Collectors.toList());

I am getting an error. Can someone provide me with a way to do it in Java8?


Solution

  • Your sniplet wil produce a List<List<String>> not List<String>.

    You are missing flatMap , that will convert stream of lists into a single stream, so basically flattens your stream:

    List<String> wordsForGivenAlphabet = words.entrySet().stream()
        .filter(x-> x.getKey().equalsIgnoreCase(inputAlphabet))
        .map(Map.Entry::getValue)
        .flatMap(List::stream) 
        .collect(Collectors.toList());
    

    You can also add distinct(), if you don't want values to repeat.