You can easily find items that are common in two lists using two ways.
def list1 = ["apple", "pear", "banana", "tomato", 1, 2]
def list2 = ["kale", "cabbage", 2, 3, "tomato", "carrot"]
The first itearates over one list, looking for each item in the second list:
def commonItems = []
list1.each { item ->
if (list2.contains(item))
commonItems.add(item)
}
println commonItems
output>> [tomato, 2]
The more idiomatic way is to use intersect()
:
def common = list1.intersect list2
println common
output>> [2, tomato]
Top comments (0)