【发布时间】:2010-03-30 09:57:03
【问题描述】:
如何比较两个列表中的项目并在 Groovy 中创建一个具有差异的新列表?
【问题讨论】:
-
你需要说出你所说的“差异”是什么意思。顺序重要吗?多份重要吗?
-
你的意思是两个列表之间的排他性析取吗?即en.wikipedia.org/wiki/Exclusive_or
标签: groovy
如何比较两个列表中的项目并在 Groovy 中创建一个具有差异的新列表?
【问题讨论】:
标签: groovy
我只是使用算术运算符,我认为发生了什么更明显:
def a = ["foo", "bar", "baz", "baz"]
def b = ["foo", "qux"]
assert ["bar", "baz", "baz", "qux"] == ((a - b) + (b - a))
【讨论】:
Collections intersect 可能会帮助您解决这个问题,即使反转它有点棘手。也许是这样的:
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
【讨论】:
我假设 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']
【讨论】:
如果是数字列表,可以这样做:
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]
【讨论】: