Using streams to group Map attributes from inner objects?

  • A+

I'm learning Java 8 - Java 11 and I got a code that I'm converting to . I have the following classes:

class Resource {    List<Capability> capabilities; }  class Capability {    String namespace;    Map<String, Object> attributes; } 

I have a stream of Resources and I want to extract all its capabilities attributes from two different namespaces ("a", "b") to a Map<Resource, Map<String, Object>> that I have sure that do not have duplicates keys.

I did many attempts using map, flatMap but with those, I can't keep a reference of the main resource object. Using the new feature of java9 I could progress, but I'm stuck on the code below where I was able to return all attributes, but in a set. I was not able yet to filter by a capability namespace and also put them in a map:

Map<Resource, Set<Object>> result =     .collect(groupingBy(t -> t, flatMapping(             resource -> resource.getCapabilities(null).stream(),             flatMapping(                     cap -> cap.getAttributes().entrySet().stream(),                     toSet())))); 

Seems that I'm on the right path.


You could instead use Collectors.toMap as the downstream :

Map<Resource, Map<String, Object>> result = pResolved         .stream()         .collect(groupingBy(Function.identity(),                 flatMapping(resource -> resource.getCapabilities().stream(),                         flatMapping(cap -> cap.getAttributes().entrySet().stream(),                                 toMap(Map.Entry::getKey, Map.Entry::getValue))))); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: