Java 8 threads combine the result of an internal thread into the thread above

This may be a perversion, but I want to combine the results of the internal thread for the thread at a higher level.

For example, we have some complex data mapping:

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

and I need to collect all the objects in a list. While I'm doing it like this:

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

But it is not beautiful. But I can’t understand how to transfer data from the inner loop to the outer loop to collect them at the end.

Can this be done without any external objects?

+4
source share
2 answers

What about:

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

You must use flatMapfor Stream-API.

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

Code not verified

+1
source

Source: https://habr.com/ru/post/1672484/


All Articles