如何在Groovy中比较两个列表

cwxwcias  于 2022-09-21  发布在  其他
关注(0)|答案(4)|浏览(233)

如何比较两个列表中的项,并在Groovy中创建一个不同的新列表?

toe95027

toe950271#

我只是使用算术运算符,我认为发生了什么要明显得多:

def a = ["foo", "bar", "baz", "baz"]
def b = ["foo", "qux"]

assert ["bar", "baz", "baz", "qux"] == ((a - b) + (b - a))
igsr9ssn

igsr9ssn2#

集合交集可能会帮助您做到这一点,即使它是一个有点棘手的逆转它。也许是这样的:

def collection1 = ["test", "a"]
def collection2 = ["test", "b"]
def commons = collection1.intersect(collection2)
def difference = collection1.plus(collection2)
difference.removeAll(commons)
assert ["a", "b"] == difference
kmbjn2e3

kmbjn2e33#

我假设操作员正在请求两个列表之间的exclusive disjunction

(**注意:**之前的两个解决方案都不处理重复项!)

如果您希望自己在Groovy中对其进行编码,请执行以下操作:

def a = ['a','b','c','c','c'] // diff is [b, c, c]
def b = ['a','d','c']         // diff is [d]

// for quick comparison
assert (a.sort() == b.sort()) == false

// to get the differences, remove the intersection from both
a.intersect(b).each{a.remove(it);b.remove(it)}
assert a == ['b','c','c']
assert b == ['d']
assert (a + b) == ['b','c','c','d']    // all diffs

使用整数列表/数组时需要注意的一点是。您可能会因为多态方法remove(int)remove(Object)而出现问题。See here for a (untested) solution

而不是重新发明轮子,只需要使用一个库(例如commons-collections):

@Grab('commons-collections:commons-collections:3.2.1')

import static org.apache.commons.collections.CollectionUtils.*

def a = ['a','b','c','c','c'] // diff is [b, c, c]
def b = ['a','d','c']         // diff is [d]

assert disjunction(a, b) == ['b', 'c', 'c', 'd']
kyxcudwk

kyxcudwk4#

If it is a list of numbers, you can do this:

def before = [0, 0, 1, 0]
def after = [0, 1, 1, 0]
def difference =[]
for (def i=0; i<4; i++){
    difference<<after[i]-before[i]
}
println difference //[0, 1, 0, 0]

相关问题