0

How do I compare two lists in groovy

[N1OB] == [ABCD9, ABCD8, ABCD7] -> should return false

[ABCD1, ABCD1, ABCD1, ABCD1] == [ABCD9, ABCD8, ABCD7] -> should return false

[ABCD1, ABCD1, ABCD1, ABCD1] == [ABCD9, ABCD8, ABCD1] -> should return true

is there any groovy function there to do this?

Thanks in advance

2 Answers 2

7

I solved by

List newList = ["ABCD9", "ABCD8", "ABCD7"]
List oldList = ["dfgdfg"]

if(newList.intersect(oldList))
println("difference->")

Think it is correct, can someone suggest

3
  • 2
    intersect is the way to go for your goal. your question should have reflected this a little more...
    – cfrick
    Sep 18, 2014 at 10:06
  • 1
    Keep in mind here that intersect does not return a boolean but the intersection of two lists. In your logic, it is Groovy Truth which kicks in to validate that there is at least on intersection. 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.disjoint(oldList). disjoint() returns a boolean.
    – dmahapatro
    Sep 18, 2014 at 13:44
  • @dmahapatro, I didn't got your point clearly, I guess intersection + groovy truth is working fine for me Sep 29, 2014 at 4:46
1

disjoint() returns false if any element in list one is in list two. If you add negation you will have:

!(['N1OB'].disjoint(['ABCD9', 'ABCD8', 'ABCD7']))  // false

!(['ABCD1', 'ABCD1', 'ABCD1', 'ABCD1'].disjoint(['ABCD9', 'ABCD8', 'ABCD7']))  // false

!(['ABCD1', 'ABCD1', 'ABCD1', 'ABCD1'].disjoint(['ABCD9', 'ABCD8', 'ABCD1']) )  // true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.