如何在Groovy中比较两个列表

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

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

toe95027

toe950271#

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

  1. def a = ["foo", "bar", "baz", "baz"]
  2. def b = ["foo", "qux"]
  3. assert ["bar", "baz", "baz", "qux"] == ((a - b) + (b - a))
igsr9ssn

igsr9ssn2#

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

  1. def collection1 = ["test", "a"]
  2. def collection2 = ["test", "b"]
  3. def commons = collection1.intersect(collection2)
  4. def difference = collection1.plus(collection2)
  5. difference.removeAll(commons)
  6. assert ["a", "b"] == difference
kmbjn2e3

kmbjn2e33#

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

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

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

  1. def a = ['a','b','c','c','c'] // diff is [b, c, c]
  2. def b = ['a','d','c'] // diff is [d]
  3. // for quick comparison
  4. assert (a.sort() == b.sort()) == false
  5. // to get the differences, remove the intersection from both
  6. a.intersect(b).each{a.remove(it);b.remove(it)}
  7. assert a == ['b','c','c']
  8. assert b == ['d']
  9. assert (a + b) == ['b','c','c','d'] // all diffs

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

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

  1. @Grab('commons-collections:commons-collections:3.2.1')
  2. import static org.apache.commons.collections.CollectionUtils.*
  3. def a = ['a','b','c','c','c'] // diff is [b, c, c]
  4. def b = ['a','d','c'] // diff is [d]
  5. assert disjunction(a, b) == ['b', 'c', 'c', 'd']
展开查看全部
kyxcudwk

kyxcudwk4#

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

  1. def before = [0, 0, 1, 0]
  2. def after = [0, 1, 1, 0]
  3. def difference =[]
  4. for (def i=0; i<4; i++){
  5. difference<<after[i]-before[i]
  6. }
  7. println difference //[0, 1, 0, 0]

相关问题