Ted*_*eid 48
我只是使用算术运算符,我认为更明显的是:
def a = ["foo", "bar", "baz", "baz"]
def b = ["foo", "qux"]
assert ["bar", "baz", "baz", "qux"] == ((a - b) + (b - a))
Run Code Online (Sandbox Code Playgroud)
Daf*_*aff 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
Run Code Online (Sandbox Code Playgroud)
Nic*_*aly 11
我假设OP要求两个列表之间的独占分离?
(注意:以前的解决方案都没有处理重复!)
如果您想在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
Run Code Online (Sandbox Code Playgroud)
一个问题是,正在使用整数列表/数组.您(可能)有问题,因为多态方法remove(int)vs remove(Object).请参阅此处了解(未经测试的)解决方案.
然而,您应该只使用现有的库(例如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']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37999 次 |
| 最近记录: |