How can I compare the items in two lists and create a new list with the difference in Groovy?
In Groovy we use the == operator to see if two objects are the same, in Java we would use the equals() method for this. To test if two variables are referring to the same object instance in Groovy we use the is() method. The !=
Benefit:- If required, you can get the common elements as def commonItems = newList. intersect(oldList) . :) If you just need to check with a boolean you can also use ! newList.
Python sort() method and == operator to compare lists Further, the == operator is used to compare the list, element by element.
I'd just use the arithmetic operators, I think it's much more obvious what's going on:
def a = ["foo", "bar", "baz", "baz"] def b = ["foo", "qux"] assert ["bar", "baz", "baz", "qux"] == ((a - b) + (b - a))
Collections intersect might help you with that even if it is a little tricky to reverse it. Maybe something like this:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With