如何在Groovy中将列表嵌套在列表内

时间:2019-06-18 03:30:32

标签: groovy nested iteration

这是我的原始json

[
  {
    "city": "houston",
    "countyName": "county1",
    "email": "county1@gmail.com"
  },
  {
    "city": "houston",
    "countyName": "county1",
    "email": "county1a@gmail.com"
  },
  {
    "city": "houston",
    "countyName": "county2",
    "email": "county2@gmail.com"
  },
  {
    "city": "dallas",
    "countyName": "county1",
    "email": "countyDallas1@gmail.com"
  },
  {
    "city": "dallas",
    "countyName": "county2",
    "email": "countyDallas2@gmail.com"
  }
]

我想转换为:

[
  {
    "city": "houston",
    "counties": [
      {
        "countyName": "county1",
        "email": [
          "county1@gmail.com",
          "county1a@gmail.com"
        ]
      },
      {
        "countyName": "county2",
        "email": [
          "county2@gmail.com"
        ]
      }
    ]
  },
  {
    "city": "dallas",
    "counties": [
      {
        "countyName": "county1",
        "email": [
          "county1@gmail.com"
        ]
      },
      {
        "countyName": "county2",
        "email": [
          "county2@gmail.com"
        ]
      }
    ]
  }
]  

我做了如下

groupBy{it.countyName}.values().collect{m-> [city: m.city[0], counties: m.counties.unique())]}  

到目前为止,我按县名分组。
之后,我得到了值。
然后我收集到新列表。
我可以获得唯一的县列表,但不知道如何嵌套为预期结果

groupBy{it.countyName}.values().collect{m-> [city: m.city[0], counties: m.counties.unique())]}  

哪个命令用于将电子邮件列表嵌套在县列表中

1 个答案:

答案 0 :(得分:1)

您应该首先按城市名称对输入列表进行分组。然后,对于每个城市,您可以将其余数据按县名分组以收集电子邮件地址列表。考虑以下示例:

table {
  border-collapse: collapse;
  width: 100%;
  table-layout: fixed;
  th,
  td {
    border: 1px solid;
    font-size: 14px;
    line-height: 20px;
    padding: 10px;
  }
  th {
    text-align: center;
  }
}

输出:

<table>
  <thead>
    <tr>
      <th>SDFSDFSDFSD</th>
      <th>SDFSDFSDF</th>
      <th>SDFSDFSDF</th>
      <th>SDFSDFSDFSDF</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>SDFSDFSDF</td>
      <td>
        DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
      </td>
      <td>-</td>
      <td>BSDFSDFSDF_</td>
    </tr>
    <tr>
      <td>SDFSDFSDFSDFSDFSDF</td>
      <td>SDFSDFSDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
        <td>SDFSDF</td>
        <td>SDFSDFSDFSDF</td>
    </tr>
    <tr>
      <td>SDFSDFSDFSDFSDFSDF</td>
      <td>
        SDFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
      </td>
      <td>1 SDFDSFSDFSDF</td>
      <td>SDFSDFSDFSD</td>
    </tr>
  </tbody>
</table>