映射嵌套列表嵌套地图中的Java 8

user1697113:
FamilyLegacy
   ParentList<Parent>

Parent //(Obj Class)
   ParentId // String ID
   ChildList<Child>  // List

Child
   ChildId
   GrandChildList<GrandChild>

GrandChild
    GrandChildId
   // Some GrandChild attribs    



{
  "parents": [
    {
      "Id": "P1",
      "parentName": "BigBob",
      "Child": [
        {
          "id": "C1",
          "name": "BOB",
          "grandChild": [
            {
              "grandChildId": "G1",
              "grandChildName": "John"
            },
            {
              "grandChildId": "G2",
              "grandChildName": "Doe"
            }
          ]
        },
        {
          "id": "C2",
          "name": "Marley",
          "grandChild": [
            {
              "grandChildId": "G3",
              "grandChildName": "Katty"
            },
            {
              "grandChildId": "G4",
              "grandChildName": "Perry"
            }
          ]
        }
      ]
    }
  ]
}

输出至 - >

{
  "P1": {
    "name": "BigBob",
    "C1": {
      "name": "Bob",
      "G1": {
        "name": "John"
      },
      "G2": {
        "name": "Doe"
      }
    },
    "C2": {
      "name": "Marey",
      "G3": {
        "name": "Katty"
      },
      "G4": {
        "name": "Parry"
      }
    }
  }
}

考虑上述嵌套对象到列表结构。有没有办法来这种结构转换为嵌套地图如

 Map<String,Map<String, Map<String,Map<String,GrandChild>>>>
ParentId -> map of Parents ->map of childs ->map of grand childs  keyed with respective IDs

比如第一级映射

  Map<String, Parent> parentMap =
    FamilyLegacy.getParents().stream().collect(
                   Collectors.toMap(Parent::getParentId,Function.identity()));

我有一个很难可视化映射和嵌套,希望如果有一种方法使用直接分组做或映射除了个别迭代列表对象

洛尼克斯:

您可以使用Collectors.groupingBy组成一个嵌套的地图:

children.stream().collect(
    Collectors.groupingBy(
        gc -> gc.getChild().getParent().getFamilyLegacy().getId(),
        Collectors.groupingBy(
            gc -> gc.getChild().getParent().getId(),
            Collectors.groupingBy(
                gc -> gc.getChild().getId()))));

你可以看到哪里筑巢用于获取密钥来自通过lambda表达式。

该类型将随后Map<String, Map<String, Map<String, GrandChild>>>第一键填充是FamilyLegacy,第二Parent,第三从Child

编辑:

从开始FamilyLegacy就可以使用Collectors.toMap,就像这样:

familyLegacy.getParents().stream().collect(
    Collectors.toMap(
        p -> p.getId(),
        p -> p.getChildList().stream().collect(
            Collectors.toMap(
                c -> c.getId(),
                c -> c.getGrandChildList().stream().collect(
                    Collectors.toMap(
                        gc -> gc.getId(),
                        Function.identity()))))));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章