Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare two lists in Groovy

Tags:

groovy

How can I compare the items in two lists and create a new list with the difference in Groovy?

like image 235
user304966 Avatar asked Mar 30 '10 09:03

user304966


People also ask

How do I compare two objects 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 !=

How do you get common elements from two lists in Groovy?

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.

Can you compare lists with ==?

Python sort() method and == operator to compare lists Further, the == operator is used to compare the list, element by element.


2 Answers

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)) 
like image 127
Ted Naleid Avatar answered Sep 27 '22 23:09

Ted Naleid


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 
like image 45
Daff Avatar answered Sep 27 '22 22:09

Daff