Sling Academy
Home/Kotlin/Checking if a List Contains a Given Value in Kotlin

Checking if a List Contains a Given Value in Kotlin

Last updated: December 05, 2024

Kotlin, a modern, open-source programming language, has been steadily gaining popularity for its expressive syntax and enhanced safety features. One common operation in programming is checking if a List contains a specific value. In this article, we will delve into various ways to accomplish this task in Kotlin, providing a comprehensive guide filled with code examples and explanations.

Using the contains() Function

The most straightforward way to check if a list contains a particular value in Kotlin is by using the contains() function. This function checks if the specified element is present in the list, returning true if it is found and false otherwise.


fun main() {
    val names = listOf("Alice", "Bob", "Charlie")
    val valueToCheck = "Bob"
    
    if (names.contains(valueToCheck)) {
        println("The list contains the value: $valueToCheck")
    } else {
        println("The list does not contain the value: $valueToCheck")
    }
}

In this example, we declare a list of names and use the contains() function to check if "Bob" is one of its elements.

Using the in Operator

Kotlin provides a more idiomatic way of checking list membership using the in operator. This operator is generally preferred for its readability and conciseness.


fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    val numberToCheck = 3

    if (numberToCheck in numbers) {
        println("The list contains the number: $numberToCheck")
    } else {
        println("The list does not contain the number: $numberToCheck")
    }
}

Here, we demonstrate the use of the in operator to determine if the number 3 is included in the list of numbers.

Sometime you might want to perform a case-insensitive check, particularly when dealing with strings. This can be achieved by converting each element and the value being checked to a common case, typically lower case.


fun main() {
    val fruits = listOf("Apple", "Banana", "Cherry")
    val fruitToCheck = "banana"

    if (fruits.any { it.equals(fruitToCheck, ignoreCase = true) }) {
        println("The list contains the fruit: $fruitToCheck")
    } else {
        println("The list does not contain the fruit: $fruitToCheck")
    }
}

In this example, we use the any() function with conditional logic to perform a case-insensitive search.

Using the filter() Function

For more complex scenarios where you might want to get all elements that match a specific condition rather than just check for existence, the filter() function comes in handy.


fun main() {
    val animals = listOf("Dog", "Cat", "Parrot", "Dog")
    val animalToFind = "Dog"

    val results = animals.filter { it == animalToFind }
    if (results.isNotEmpty()) {
        println("The list contains the animal: $animalToFind")
        println("Number of occurrences: ${results.size}")
    } else {
        println("The list does not contain any animal: $animalToFind")
    }
}

Here, we use filter() to obtain a new list of all matches, providing insight into how frequent a given value is within the list.

Conclusion

In conclusion, Kotlin offers a variety of methods to check if a List contains a specific value, each with its own advantages depending on your requirements. Whether you prefer the straightforward contains() function, the elegant in operator, a case-insensitive approach, or leveraging filter() for deeper analysis, Kotlin provides the tools necessary to efficiently handle list operations.

By mastering these methods, you'll be better equipped to manipulate lists effectively in your Kotlin programs. Explore these functions and integrate them into your projects to perform list checks seamlessly.

Next Article: Introduction to Sets in Kotlin

Previous Article: Reversing and Shuffling Lists in Kotlin

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin