Serdar Çivi
Serdar Çivi

Reputation: 331

Can i check if condition is true for all elements in a list on Kotlin?

How can i check in if statement that condition is true for elements in a collection

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)
    }
}

i only write 2 conditions for convenience

Upvotes: 9

Views: 13570

Answers (3)

AlexT
AlexT

Reputation: 2964

Not sure if you want to check if the condition is true for ALL the elements, or you just want to know which ONE in particular is true, or if ANY are true.

In the first scenario, where we want to know if ALL of them

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

The second scenario we can do a simple .map, to know each one individually.

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

And if we want to check if ANY are true, we can do:

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

Edit since Todd mentioned none in the comments, I'll add a few other similar functions in case it would help others with similar questions.

Firstly, we don't actually need a list, all of these funcitons can work on the range directly (the ones above and the ones below)

val result = (1..20).all { it % 2 == 0 }

Other similar functions:

none - the opposite of all.

filter - will keep all elements for which the predicate is true.

filterNot - will keep all elements for which the predicate is false.

Upvotes: 22

Serdar &#199;ivi
Serdar &#199;ivi

Reputation: 331

Change my code to this if anyone interested

fun main() {
    var count = 20
    var flag = false
    val list = (1..20).toList()
    while (true){
        count++
        if (list.all { count % it == 0 }){
            println(count)
            break
        }
    }
}

Upvotes: 2

ulou
ulou

Reputation: 5853

For example you can use filter:

fun main() {
    val list = mutableListOf<Int>()

    for (i in 1..20)
        list.add(i)

    list.filter { it % 2 === 1 }
        .forEach { println(it) }
}

Upvotes: 1

Related Questions