Reputation: 736
I have an array of array list, I am trying to structure it using groovy but I am not getting the expected result, I have used putALL
method to add an array but it is overriding the previous array,
I have tried this way and the output is this [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())
My goal is if there are any same coverageType values in the array I will add them to the child list,
This is my expected output:
[ parent: 'health',
children: [
[
coverageType: 'health',
amount:'9',
expireDate: '2020'
],
[
coverageType: 'health',
amount:'9',
expireDate: '2021'
],
]
],
[
parent: 'insurance',
children: [
[
coverageType: 'insurance',
amount: '9',
expireDate: '2020'
]
]
],
Or without key:
[ parent: 'health',
children: [
[
'health',
'9',
'2020'
],
[
'health',
'9',
'2021'
],
]
],
[
parent: 'insurance',
children: [
[
'insurance',
'9',
'2020'
]
]
],
Upvotes: 0
Views: 271
Reputation: 24498
Given this:
def fakeList = [
[coverageType: 'health', amount: 9, expireDate: 2020],
[coverageType: 'insurance', amount: 10, expireDate: 2020],
[coverageType: 'health', amount: 9, expireDate: 2021],
]
Consider this:
def groupList = fakeList.groupBy { it.coverageType }
.collect { coverageType, items ->
def map = [:]
map.'parent' = coverageType
map.'childs' = items.collect { item ->
def childMap = [:]
childMap.'coverage' = coverageType
childMap.'amount' = item.amount as String
childMap.'expireDate' = item.expireDate as String
childMap
}
map
}
The resulting map is:
[
[parent:health, childs:[[coverage:health, amount:9, expireDate:2020], [coverage:health, amount:9, expireDate:2021]]],
[parent:insurance, childs:[[coverage:insurance, amount:10, expireDate:2020]]]
]
Working example listed here, which also converts to JSON for pretty-printing.
Upvotes: 1