kotlin

Check if item exists in an Array Kotlin

In this post, we are going to explain the methods that can be used to check whether an item exists in an Array or ArrayList.

fun checkItem(arr: Array<String>, item: String): Boolean {
    if (arr.indexOf(item) != -1) {
        return true
    } else {
        return false
    }
}

fun main() {
    // create an array
    val students = arrayOf<String>("Jacob", "Roy", "Yamini", "Neha")
    
    // Check if Roy is in the array
    val check_roy: Boolean = checkItem(students, "Roy")
    println("Roy exists: " + check_roy)
    
    // Check if Sohan is in the array
    val check_sohan: Boolean = checkItem(students, "Sohan")
    println("Sohan exists: " + check_sohan)
}

Output

Roy exists: true
Sohan exists: false

Explanation

  1. We have created an array named students that contain multiple items in String format.
  2. Created a function named checkItem() that takes two parameters Array and item. We are using Array.indexOf() function inside the checkItem() function to get the index of the item.
  3. The checkItem() function will return true if the item exists in the Array and returns false if not.
  4. We are checking for two different items if they exist in the given array or not and print the result.

Check if an item exists in ArrayList

If you are using Array List in Kotlin which is a mutable list and can be used to add or delete items easily using Kotlin built-in functions. You can also check if an item exists in an ArrayList or not using ArrayList.indexOf() function.

fun main() {
    // initiaize array list
    val students = ArrayList<String>()
    
    students.add("Jacob")
    students.add("John")
    students.add("Somar")
    
    if (students.indexOf("John") !== -1) {
        println("Item exists in the array list")
    } else {
        println("item does not exist in the array list")
    }
}

Output

Item exists in the array list
Was this helpful?