我可以检查 Kotlin 上列表中的所有元素的条件是否都为 true 吗?

Ser*_*ivi 8 kotlin

我如何检查集合中元素的条件是否成立的 if 语句

fun main() {
    var control = 20
    val list = mutableListOf<Int>()
    for (i in 1..20)
        list.add(i)
    while (true) {
        control++
        if (control % list[0] == 0 && control % list[1] == 0)
    }
}
Run Code Online (Sandbox Code Playgroud)

为了方便我只写了2个条件

Ale*_*exT 19

不确定您是否想检查条件是否对所有元素都为真,或者您只想知道哪一个为真,或者是否有任何为真。

在第一个场景中,我们想知道是否所有的

val list = (1..20).toList() //a bit easier to create the list this way
val result = list.all { control % it == 0 }
println(result) //will print true if all of the elements are true, and false if at least one is false
Run Code Online (Sandbox Code Playgroud)

第二种情况我们可以做一个简单的 .map,来单独了解每个。

val list = (1..20).toList()
val result = list.map { control % it == 0 }
println(result) //will print a list of type (true, false, true, etc) depending on each element
Run Code Online (Sandbox Code Playgroud)

如果我们想检查 ANY 是否为真,我们可以这样做:

val list = (1..20).toList()
val result = list.any { control % it == 0 }
println(result) //will print true if any of the elements are true, and false if all of the elements are false
Run Code Online (Sandbox Code Playgroud)

自从托德在评论中提到以来进行编辑none,我将添加一些其他类似的功能,以防它可以帮助其他人解决类似的问题。

首先,我们实际上不需要列表,所有这些函数都可以直接在范围上工作(上面的和下面的)

val result = (1..20).all { it % 2 == 0 }
Run Code Online (Sandbox Code Playgroud)

其他类似功能:

none- 的相反all

filter- 将保留谓词为真的所有元素。

filterNot- 将保留谓词为假的所有元素。