SoulCub
SoulCub

Reputation: 467

Java 8 streams merge inner stream result to stream above

Maybe it's perversion but I want to merge results of inner stream to stream on the level above.

For example we have some complex map with data:

Map<String, List<Map<String, Object>>> dataMap

and I need to collect all Objects to List. For now I'm doing like this:

Set<Object> segmentIds = new HashSet<>();
dataMap.values().forEach(maps -> maps.forEach(map -> segmentIds.add(map.get("object"))));

But it's not prettily way. But I can't understand how to transfer data from inner cycle to outer to collect them in the end.

Is it possible to do it without any outer objects?

Upvotes: 4

Views: 2053

Answers (2)

Roma Khomyshyn
Roma Khomyshyn

Reputation: 1152

What about it:

Set<Object> collect = dataMap.values()
            .stream()
            .flatMap(Collection::stream)
            .map(map -> map.get("object"))
            .collect(Collectors.toSet());

Upvotes: 6

Stefan Warminski
Stefan Warminski

Reputation: 1835

You have to use flatMapof the Stream-API.

List<Object> allObjects = dataMap.values().stream()
    .flatMap(l -> l.stream())
    .flatMap(m -> m.values().stream())
    .collect(Collectors.toList())

Code is not tested

Upvotes: 1

Related Questions