Skip to main content

How to check if an ArrayList contains a specific element in Kotlin

How to check if an ArrayList contains a specific element in Kotlin.

Here's a detailed step-by-step tutorial on how to check if an ArrayList contains a specific element in Kotlin:

  1. Create an ArrayList:

    val arrayList = ArrayList<String>()
  2. Add elements to the ArrayList:

    arrayList.add("apple")
    arrayList.add("banana")
    arrayList.add("orange")
  3. Use the contains() function to check if the ArrayList contains a specific element:

    val element = "banana"
    val containsElement = arrayList.contains(element)

    In this example, we are checking if the ArrayList contains the element "banana". The contains() function returns true if the element is found in the ArrayList, and false otherwise.

  4. Print the result:

    if (containsElement) {
    println("The ArrayList contains the element $element")
    } else {
    println("The ArrayList does not contain the element $element")
    }

    This will print either "The ArrayList contains the element banana" or "The ArrayList does not contain the element banana" depending on the result of the contains() function.

  5. You can also check if an ArrayList contains an element using an if statement directly:

    val element = "banana"
    if (element in arrayList) {
    println("The ArrayList contains the element $element")
    } else {
    println("The ArrayList does not contain the element $element")
    }

    This will produce the same result as the previous example.

That's it! You now know how to check if an ArrayList contains a specific element in Kotlin.