Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 632
user1639485 Avatar asked Jul 18 '17 21:07

user1639485


2 Answers

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.

like image 117
Beri Avatar answered Sep 27 '22 20:09

Beri


Federico is right in his comment, if all you want is to get the values of a certain key (inside a List) why don't you simply do a get (assuming all your keys are uppercase letters already) ?

 List<String> values = words.get(inputAlphabet.toUpperCase());

If on the other hand this is just to understand how stream operations work, there is one more way to do it (via java-9 Collectors.flatMapping)

List<String> words2 = words.entrySet().stream()
            .collect(Collectors.filtering(x -> x.getKey().equalsIgnoreCase(inputAlphabet),
                    Collectors.flatMapping(x -> x.getValue().stream(), 
                          Collectors.toList())));
like image 34
Eugene Avatar answered Sep 27 '22 20:09

Eugene