使用Java 8 Streams将模型列表转换为带有内部映射的Map

时间:2016-11-02 13:07:44

标签: java java-8 java-stream

我有List<Model>

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

我希望将其转换为地图<String, Map<String, List<String>>>

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

我试过这个:

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

但是遇到了一些有线编译错误..我缺少什么?

编辑:添加了错误的屏幕截图: enter image description here

1 个答案:

答案 0 :(得分:3)

您的解决方案会返回不同的类型:

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

要实现您的目标,您需要在mapping(mapper, downstream)之前将List<Model>变为List<String>

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