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

user1639485 picture user1639485 · Jul 18, 2017 · Viewed 21.5k times · Source

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?

Answer

Beri picture Beri · Jul 18, 2017

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.