Mei Mei - 1 year ago 67
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:

String name
String someId
ImmutableMap<SomeCategory, ImmutableList<SomeClassB>> someMap

(the immutable collections are from:

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?

.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 Source

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

    .flatMap(objA -> objA.getSomeMap().entrySet().stream())
    .filter(entry -> "something".equals(entry.getKey()))
    .flatMap(entry -> entry.getValue().stream())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download