如何比较Groovy中的两个列表

时间:2010-03-30 09:57:03

标签: groovy

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

4 个答案:

答案 0 :(得分:48)

我只是使用算术运算符,我认为发生的事情更为明显:

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

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

答案 1 :(得分:38)

集合相交可能对你有所帮助,即使反转它有点棘手。也许是这样的:

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

答案 2 :(得分:10)

我认为OP要求两个列表之间的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)vs 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']

答案 3 :(得分:0)

如果它是数字列表,则可以执行以下操作:

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]