如何获取groovy中嵌套映射的差异?

问题描述 投票:0回答:1

如何获取嵌套映射的差异?我不知道如何得到它。在我的地图中有 2 个元素:response1 和 response2。在 response1 中,size() 中有 5 个,在 response2 中,size() 中有 3 个。我想打印出每个元素的差异以及缺失的元素

我的代码:

def map = [response1:[[code:PLACE1, date:20-Jan-2021,
[code:PLACE2, date:20-Feb-2021],
[code:PLACE3, date:20-Mar-2021],
[code:PLACE4, date:20-Apr-2021],
[code:PLACE5, date:20-May-2021]],
response2:[[code:PLACE1, date:21-Jan-2021,
[code:PLACE2, date:20-Feb-2021],
[code:PLACE3, date: 20-Mar-2021]]]


def diff1 = map['response1'].minus(map['response2'])
def diff2 = map['response2'].minus(map['response1'])

echo "${diff1}\n"
echo "${diff2}\n"

实际产量:

[[code:PLACE2, date:20-Feb-2021],
[code:PLACE4, date:20-Apr-2021],
[code:PLACE5, date:20-May-2021]]


[[code:PLACE2, date:20-Feb-2021],
[code:PLACE3, date: 20-Mar-2021]]

预期产出:

[[date:20-Jan-2021],
[code:PLACE4, date:20-Apr-2021],
[code:PLACE5, date:20-May-2021]] 

[[date:21-Jan-2021],
groovy maps difference
1个回答
0
投票

我相信您所追求的是某种可用于嵌套地图和列表的

minus
功能。这是一种使用递归产生预期结果的方法。

def minus(left, right) {
    if (left == right) {
        return [:]
    } else {
        switch (left) {
            case Map:
                if (!(right instanceof Map)) {
                    return left
                } else {
                    return left.findAll { k, v -> !right.containsKey(k) } \
                           + left.findAll { k, v -> right.containsKey(k) && v != right[k] }
                                    .collectEntries { k, v -> [k, minus(v, right[k])] }
                }
            case List:
                if (!(right instanceof List)) {
                    return left
                } else {
                    return left.withIndex().with {
                        it.findAll { val, index -> index < right.size() && val != right[index] }
                                .collect { val, index -> minus(val, right[index]) } \
                        + it.findAll { val, index -> index >= right.size() }
                                .collect { val, index -> val }
                    }
                }
            default:
                return left
        }
    }
}

def response1 = [[code: "PLACE1", date: "20-Jan-2021"],
                 [code: "PLACE2", date: "20-Feb-2021"],
                 [code: "PLACE3", date: "20-Mar-2021"],
                 [code: "PLACE4", date: "20-Apr-2021"],
                 [code: "PLACE5", date: "20-May-2021"]]

def response2 = [[code: "PLACE1", date: "21-Jan-2021"],
                 [code: "PLACE2", date: "20-Feb-2021"],
                 [code: "PLACE3", date: "20-Mar-2021"]]

assert minus(response1, response2) == [['date': '20-Jan-2021'], ['code': 'PLACE4', 'date': '20-Apr-2021'], ['code': 'PLACE5', 'date': '20-May-2021']]
assert minus(response2, response1) == [['date': '21-Jan-2021']]
© www.soinside.com 2019 - 2024. All rights reserved.