Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 544
SoulCub Avatar asked Mar 10 '23 14:03

SoulCub


2 Answers

What about it:

Set<Object> collect = dataMap.values()
            .stream()
            .flatMap(Collection::stream)
            .map(map -> map.get("object"))
            .collect(Collectors.toSet());
like image 162
Roma Khomyshyn Avatar answered Mar 14 '23 10:03

Roma Khomyshyn


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

like image 38
Stefan Warminski Avatar answered Mar 14 '23 12:03

Stefan Warminski