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:
Create an ArrayList:
val arrayList = ArrayList<String>()Add elements to the ArrayList:
arrayList.add("apple")
arrayList.add("banana")
arrayList.add("orange")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 returnstrueif the element is found in the ArrayList, andfalseotherwise.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.You can also check if an ArrayList contains an element using an
ifstatement 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.