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

4

我有一个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

2
请在您的问题中包含编译错误。 - khelwood
1个回答

3

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

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

为了实现您想要的功能,您需要使用mapping(mapper, downstream)方法将List<Model>转换为List<String>。请注意保留原有的HTML标签。
Map<String, Map<String, List<String>>> r = currentlyReportingAgents.stream()
    .collect(groupingBy(Model::getParent,
                        groupingBy(Model::getChild, mapping(Model::getChild, toList()))));

不错。添加 r.forEach((k, v) -> System.out.println(k + " :: " + v)); 就会有所作为。 - mohsenmadi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接