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?
What about it:
Set<Object> collect = dataMap.values()
.stream()
.flatMap(Collection::stream)
.map(map -> map.get("object"))
.collect(Collectors.toSet());
You have to use flatMap
of 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With