0
0
KotlinHow-ToBeginner · 3 min read

How to Check if List Contains Element in Kotlin

In Kotlin, you can check if a list contains an element using the contains() function or the in keyword. Both return a Boolean value indicating if the element is present in the list.
📐

Syntax

The two common ways to check if a list contains an element are:

  • list.contains(element): Calls the contains() function on the list.
  • element in list: Uses the in keyword for a more readable check.

Both return true if the element is found, otherwise false.

kotlin
val list = listOf("apple", "banana", "cherry")

// Using contains()
val hasBanana = list.contains("banana")

// Using 'in' keyword
val hasOrange = "orange" in list
💻

Example

This example shows how to check if a list contains certain fruits using both contains() and in. It prints the results to the console.

kotlin
fun main() {
    val fruits = listOf("apple", "banana", "cherry")

    if (fruits.contains("banana")) {
        println("Banana is in the list.")
    } else {
        println("Banana is not in the list.")
    }

    if ("orange" in fruits) {
        println("Orange is in the list.")
    } else {
        println("Orange is not in the list.")
    }
}
Output
Banana is in the list. Orange is not in the list.
⚠️

Common Pitfalls

Some common mistakes when checking list membership include:

  • Using == to compare the whole list instead of checking elements.
  • Forgetting that contains() and in are case-sensitive for strings.
  • Trying to check for an element in a null list without safe calls.

Always ensure the list is not null or use safe calls like list?.contains(element).

kotlin
val list: List<String>? = null

// Unsafe call - will cause error if list is null
// val hasApple = list.contains("apple") // Error

// Safe call to avoid error
val hasAppleSafe = list?.contains("apple") ?: false
📊

Quick Reference

MethodDescriptionExample
contains()Checks if list contains elementlist.contains("item")
in keywordChecks if element is in list"item" in list
Safe callAvoids null pointer when list may be nulllist?.contains("item") ?: false

Key Takeaways

Use contains() or in keyword to check if a list contains an element.
Both methods return a Boolean: true if found, false otherwise.
Remember that string checks are case-sensitive.
Use safe calls to avoid errors when the list might be null.
Avoid comparing the whole list with == when checking for an element.