Christian Christian - 1 month ago 7
Java Question

Transforming a list of Models into a Map with an inner map using Java 8 Streams

I have a List of Objects:

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


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

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


I've 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 wired compilation errors.. What am I missing?

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

Answer

Your solution returns a different type:

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

To achieve what you want, you need to turn a List<Model> into a List<String> by the mapping(mapper, downstream):

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