gpt4 book ai didi

java - 如何从重复的映射值生成唯一键

转载 作者:行者123 更新时间:2023-12-02 01:36:28 26 4
gpt4 key购买 nike

我有一个包含 map 列表的 JSON:

{
"aprLimits": [{
"orgId": "Company 1",
"rangeStart": "54936",
"rangeEnd": "54936",
"amountLimit": 100000
}, {
"orgId": "Company 1",
"rangeStart": "59434",
"rangeEnd": "59434",
"amountLimit": 0.01
}, {
"orgId": "Company 1",
"rangeStart": "54345",
"rangeEnd": "54345",
"amountLimit": 0
}, {
"orgId": "Company 1",
"rangeStart": "54345",
"rangeEnd": "54345",
"amountLimit": 250000
}, {
"orgId": "Company 2",
"rangeStart": "043",
"rangeEnd": "043",
"amountLimit": 0.01
}, {
"orgId": "Company 2",
"rangeStart": "042",
"rangeEnd": "042",
"amountLimit": 1000
}, {
"orgId": "Company 2",
"rangeStart": "032",
"rangeEnd": "032",
"amountLimit": 0
}]}

我的目标是通过将其转换为键并将其余值分配给它来收集与唯一 orgId 相对应的数据,因此最终结果如下所示:

["Company 1": [[54936, 54936, 100000], [59434, 59434, 0.01], [54345, 54345, 0], [54345, 54345, 250000]], "Company 2": [[043, 043, 0.01], [042, 042, 1000], [032, 032, 0]]]

我已经获取了唯一的 orgId 并将数据收集到列表中,但我无法弄清楚如何将唯一键与列表关联

def slurper = new JsonSlurper()
def parsedJson = slurper.parseText(json)
def list = []
def orgIds = parsedJson.aprLimits.orgId.unique()

parsedJson.aprLimits.each {
if (orgIds.contains(it.orgId)) {
data = new ArrayList(Arrays.asList(it.rangeStart, it.rangeEnd, it.amountLimit))
list.add(data)
}}

最佳答案

这里一个好的开始是groupBy,然后塑造你想要的数据。更短的是带有默认值的映射的reduce。例如

parsedJson.aprLimits.inject(
[:].withDefault{[]} // if a key is missing, add it and make the value an empty vector
){ r, v ->
r[v.orgId] << [v.rangeStart, v.rangeEnd, v.amountLimit]
r
}

关于java - 如何从重复的映射值生成唯一键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55202202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com