【发布时间】:2022-12-14 00:55:56
【问题描述】:
我有一个数组列表数组,我正在尝试使用 groovy 构建它,但没有得到预期的结果,我使用 putALL 方法添加一个数组,但它覆盖了以前的数组,
我试过这种方式,输出是这个[parent:health, children:[true]]
import java.util.stream.Collectors
def fakeList = [
[coverageType: 'health', amount: 9, expireDate: 2020],
[coverageType: 'insurance', amount: 10, expireDate: 2020],
[coverageType: 'health', amount: 9, expireDate: 2021],
]
def groupList = [:]
def list = fakeList
.stream()
.map { item ->
def parentWithChilds = [
parent: item.coverageType,
child: groupList.stream()
.map { list -> list?.parent !== item.coverageType }
.collect(Collectors.toList())
]
groupList.putAll(parentWithChilds)
}.collect(java.util.stream.Collectors.toList())
我的目标是,如果数组中有任何相同的 coverageType 值,我会将它们添加到子列表中,
这是我的预期输出:
[ parent: 'health',
children: [
[
coverageType: 'health',
amount:'9',
expireDate: '2020'
],
[
coverageType: 'health',
amount:'9',
expireDate: '2021'
],
]
],
[
parent: 'insurance',
children: [
[
coverageType: 'insurance',
amount: '9',
expireDate: '2020'
]
]
],
或者没有钥匙:
[ parent: 'health',
children: [
[
'health',
'9',
'2020'
],
[
'health',
'9',
'2021'
],
]
],
[
parent: 'insurance',
children: [
[
'insurance',
'9',
'2020'
]
]
],
【问题讨论】: