Is there any equivalent Kotlin function to Java 8 Stream limit function

Omar Ham :

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.

s1m0nw1 :

Kotlin, by default, does these kind of operations eagerly whereas Streams in Java are lazy. You can have the same behaviour in Kotlin if you work with sequences, which can easily be generated from Arrays or Iterables with asSequence().

arr.asSequence().filter { i ->
    println("Filter: $i")
    i % 2 == 0
}.take(2).toList()

//Filter: 0
//Filter: 1
//Filter: 2

Note that the sequence has to be transformed back to a list in the end.

You can read about the details here.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=472227&siteId=1
Recommended