This article explores different ways to find the common items in two lists in Kotlin, where the returned collection preserves the iteration order of elements in the first list.

1. Using intersect() function

The intersect() function returns a set containing all elements that are contained in both the first list and the second list. Here’s what the code would look like:

Download Code

2. Using retainAll() function

Alternatively, you can use the retainAll() library function to remove elements from the first list that are missing in the second list. The following solution transforms the first list into a set to avoid any modifications to it, and then calls the retainAll() function on it to retain only the elements that are contained in the second list.

Download Code

3. Using filter() function

The idea here is to filter the elements that are contained in the second list. This can be easily done using the filter() function with the contains() function.

Download Code

That’s all about finding the common items in given lists in Kotlin.