Skip to content

Latest commit

 

History

History
104 lines (69 loc) · 2.75 KB

102.md

File metadata and controls

104 lines (69 loc) · 2.75 KB

Kotlin 程序:检查数组是否包含给定值

原文: https://www.programiz.com/kotlin-programming/examples/array-contains-value

在此程序中,您将学习如何在 Kotlin 中检查数组是否包含给定值。

示例 1:检查Int数组是否包含给定值

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 is found.")
    else
        println("$toFind is not found.")
}

运行该程序时,输出为:

3 is found.

在上面的程序中,我们有一个整数数组,存储在变量num中。 同样,要找到的编号存储在toFind

现在,我们使用for-in循环遍历num的所有元素,并分别检查toFind是否等于n

如果是,我们将found设置为true,然后退出循环。 如果不是,我们转到下一个迭代。


示例 2:使用Stream检查数组是否包含给定值

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 is found.")
    else
        println("$toFind is not found.")
}

运行该程序时,输出为:

7 is not found.

在上面的程序中,我们没有使用foreach循环,而是将数组转换为IntStream并使用其anyMatch()方法。

anyMatch()方法采用返回布尔值的谓词,表达式或函数。 在我们的情况下,谓词将流中的每个元素ntoFind进行比较,然后返回truefalse

如果元素n中的任何一个返回true,则将found设置为true


示例 3:检查数组是否包含非原始类型的给定值

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 is found.")
    else
        println("$toFind is not found.")
}

运行该程序时,输出为:

Four is found.

在上面的程序中,我们使用了非原始数据类型String,并使用Arraysstream()方法首先将其转换为流,然后使用anyMatch()检查数组是否包含给定值toFind

以下是等效的 Java 代码:检查数组是否包含给定值的 Java 程序