Christian Christian - 1 year ago 77
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
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 Source

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 =
                        groupingBy(Model::getChild, mapping(Model::getChild, toList()))));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download