This article explores different ways to check if a value exists in a Kotlin List.

1. Using in operator

The shortest and most idiomatic way to check whether a List contains a given value is using the in operator. It can be used as follows:

Download Code

 
Note that in operator is equivalent to calling the contains() function. The expression a in b is translated to a.contains(b).

Download Code

 
For frequent calls, it’s better to convert the list into a set and call the contains() function on it.

Download Code

 
For a list of custom objects, don’t forget to override the equals and hashCode functions. For a data class, this is not needed, as it automatically derives the equals and hashCode.

2. Using filter() function

Alternatively, you can use the filter() function to filter the given value in the list and check if the resultant list is not empty. Here’s a working example:

Download Code

 
You may also use the any() extension function to conditionally search a value in a List:

Download Code

 
To search for multiple items in the list, you can do like:

Download Code

 
The code can be shortened by making use of the functional reference for the in operator:

Download Code

3. Using Loop

Finally, you can write your custom logic for searching a value in the list using a loop. Here’s what the code would look like:

Download Code

That’s all about checking if a value exists in a Kotlin List.