web-dev-qa-db-ja.com

Groovyで2つのリストを比較するにはどうすればよいですか

2つのリストの項目を比較して、Groovyの違いを含む新しいリストを作成するにはどうすればよいですか?

23
user304966

コレクションが交差することは、それを元に戻すのが少し難しい場合でも、それを助けるかもしれません。多分このようなもの:

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
39
Daff

私は算術演算子を使用するだけです、何が起こっているのかははるかに明白です:

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

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

OPが2つのリスト間で 排他的論理和 を要求していると思いますか?

注:以前のソリューションはどちらも重複を処理しません!)

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

1つの問題は、intのリスト/配列を使用することです。ポリモーフィックなメソッドremove(int)と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']
11
Nick Grealy

それが数字のリストである場合、これを行うことができます:

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]
0
Mate Mrše