Java 8 map to only value type collection

133 views Asked by At

I want to convert my Map <K,V> into only a Set <V>. I could not find any example anywhere, including Oracle's documentation here: https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html All I could go further is:

myMap.entrySet().parallelStream().
                filter((entry) -> entry.getKey().startsWith("a"))
                .collect(Collectors.toSet());

This returns a Set of Map.Entry. In this example it's Map<String, String> so I would only expect it to return the value bit (String), I have tried .collect(Collectors.toSet(HashMap::getValue)) but that didn't work. So what am I missing here?

1

There are 1 answers

1
Tagir Valeev On BEST ANSWER

You have to add one more step to map to values:

myMap.entrySet().parallelStream()
            .filter(entry -> entry.getKey().startsWith("a"))
            .map(entry -> entry.getValue())
            .collect(Collectors.toSet());