5 different ways in Kotlin to find a string in a list of strings

Kotlin program to find a string in a list of strings :

In this post, we will learn how to find a string in a list of strings in Kotlin. We will write one program that will take one list of strings and find out another string in this list. In Kotlin, we can find a value in a list in different ways. Here, I will show you multiple ways to solve it.

Method 1: Using a for loop:

We can use one loop to iterate through the strings of the list. We can compare each string with the given string. If it is found, one flag can be marked as true and based on that flag, we can say the given string is in the list or not.

fun main(args: Array<String>) {
    val givenList = listOf("one", "two", "three", "four", "five", "six")
    var found = false
    val givenStr = "five"

    for (item in givenList) {
        if (item.equals(givenStr)) {
            found = true
            break
        }
    }

    if(found){
        print("Given word is present in the list")
    }else{
        print("Given word is not found in the list")
    }
}

Method 2: Using find or first:

find can be used to find a specific element in a list using a predicate. Using the predicate, we can check if any element is equal to a string. It returns the first element that matches the given predicate.

fun main(args: Array<String>) {
    val givenList = listOf("one", "two", "three", "four", "five", "six")
    val givenStr = "five"

    val foundValue = givenList.find { item -> item == givenStr }

    if(foundValue != null){
        print("Given word is present in the list")
    }else{
        print("Given word is not found in the list")
    }
}

It returns null if the element is not found in the list. Similarly, we can also use first.

Method 3: Using indexOf or indexOfFirst :

indexOf returns the index of the passed string if it is found in the list. If it is not found, it returns -1.

val index = givenList.indexOf(givenStr)

Method 4: Using contains:

contains returns true if the string is found. Else, it returns false.

givenList.contains(givenStr)

Method 5: Using filter:

filter returns one array by filtering out the elements based on a given predicate.

givenList.filter { item -> item == givenStr }

If the return array contains no element, we can say that the string is not found in the list.

Conclusion:

Kotlin provides different ways to solve a problem. You can go with any of the method that we defined above.

You might also like: