DEV Community

ouryperd
ouryperd

Posted on

Find common items in two lists with Groovy

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"]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

The more idiomatic way is to use intersect():

def common = list1.intersect list2
println common

output>> [2, tomato]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)