English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Program to Check if Array Contains Given Value

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to check if an array contains a given value in Kotlin.

Example1:Check if the Int array contains a given value

fun main(args: Array<String>) {
    val num = intArrayOf(1, 2, 3, 4, 5)
    val toFind = 3
    var found = false
    for (n in num) {
        if (n == toFind) {
            found = true
            break
        }
    }
    if (found)
        println("$toFind found.")
    else
        println("$toFind not found.")
}

When running the program, the output is:

3 Found.

In the above program, we have an integer array stored in the variable num, similarly, the number to be found is also stored in toFind.

Now, we use for-In the loop to traverse all elements of num, and check each one individually to see if it is equal to n.

If it does, we set found to true and exit the loop. If not, we move to the next iteration.

Example2:Use Stream to check if the array contains a given value

import java.util.stream.IntStream
fun main(args: Array<String>) {
    val num = intArrayOf(1, 2, 3, 4, 5)
    val toFind = 7
    val found = IntStream.of(*num).anyMatch { n -> n == toFind }
    if (found)
        println("$toFind Found.")
    else
        println("$toFind Not Found.")
}

When running the program, the output is:

7 Not found.

In the above program, we did not use a foreach loop, but converted the array to IntStream and used its anyMatch() method.

Returns a boolean expression or anyMatch() function. In our example, the predicate compares each element n in the stream with toFind and returns true or false.

If any element n returns true, then found is also set to true.

Example3:Check if the array contains a given value of non-primitive type

import java.util.Arrays
fun main(args: Array<String>) {
    val strings = arrayOf("One", "Two", "Three", "Four", "Five")
    val toFind = "Four"
    val found = Arrays.stream(strings).anyMatch { t -> t == toFind }
    if (found)
        println("$toFind Found.")
    else
        println("$toFind Not Found.")
}

When running the program, the output is:

Four Found.

In the above program, we use a non-primitive data type String and use the Arrays.stream() method to first convert it to a stream, and anyMatch() checks if the array contains the given toFind value.

The following is the equivalent Java code:Java Program to Check if Array Contains Given Value.

Comprehensive Collection of Kotlin Examples