Mei Mei - 2 months ago 10
Java Question

Filtering through a stream of maps and collecting into a single list?

I'm still new to streams in Java, having trouble wrapping my mind around how to convert this into a single list or set:

I get sent in a List of SomeClassA objects which has a bunch of fields:

SomeClass:
String name
String someId
...
ImmutableMap<SomeCategory, ImmutableList<SomeClassB>> someMap


(the immutable collections are from: com.google.common.collect)

Given a list of SomeClassA, I want the result to be a single set of SomeClassB.

So a list of SomeClassA comes in, and I want to be able to go through it and get someMap, then filter out only certain categories, get out the list of SomeClassB, and then in the end combine all the lists.

I've tried a few different combinations of filters and maps, but always end up with the wrong types or extra streams. What's a simple way to do this?

return listOfSomeClassA.stream()
.map(objA -> objA.getSomeMap())
. // filter someMap entries by the map's keys of category - someCategory.equals("something")
. // put together all the lists of those categories == something??

Answer

There is a built in filter method to filter out a stream by some condition. If it evaluates to false it will be removed.

return listOfSomeClassA.stream()
    .flatMap(objA -> objA.getSomeMap().entrySet().stream())
    .filter(entry -> "something".equals(entry.getKey()))
    .flatMap(entry -> entry.getValue().stream())
    .collect(Collectors.toList());