Convert a list of models to a map with an internal map using Java 8 threads

I have List<Model>:

[
  {parent: "parent", child: "child1", sensor: "wohoo"}, 
  {parent: "parent", child: "child1", sensor: "bla"}, 
  {parent: "parent", child: "child2", sensor: "wohoo2"}
]

and I want to convert it to a map <String, Map<String, List<String>>>.

 {
   parent: {
    child1: ["wohoo", "bla"],
    child2: ["wohoo2"]  
   },
 }

I tried this:

 Map<String, Map<String, List<String>>> test = currentlyReportingAgents
      .stream()
      .collect(Collectors.groupingBy(
        Model::getParent,
        Collectors.groupingBy(Model::getChild, Collectors.toList())));

but got some errors in wired compilation. What am I missing?

Edit: Added screenshot of the error: enter image description here

+4
source share
1 answer

Your solution returns a different type:

Map<String, Map<String, List<Model>>> = ...;

To achieve what you want, you need to turn List<Model>in List<String>with mapping(mapper, downstream):

Map<String, Map<String, List<String>>> r = currentlyReportingAgents.stream()
    .collect(groupingBy(Model::getParent,
                        groupingBy(Model::getChild, mapping(Model::getChild, toList()))));
+3
source

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


All Articles