I am trying to find the first two elements in a list that meet a condition (filtering), for that purpose I have implemented the following piece of code in kotlin:
val arr = 0 until 20
val res = arr.filter { i ->
println("Filter: $i")
i % 2 == 0
}.take(2)
Everything was fine until I realized it filters through the whole list, no matter if the two elements have been found.
Making use of Java 8 stream api, it works as expected.
val res2 = arr.toList().stream()
.filter { i ->
println("Filter: $i")
i % 2 == 0
}.limit(2)
So my questions is if it can be achieved using only Kotlin functions.
I know I could use a simple for loop but I want to use a functional programming aproach.