Difference between takeWhile () and filter () in Kotlin

I was doing the exercise and I found that I can get the same result using the method takeWhile()and filter()therefore I would like to know when I should use one or the other.

Thank you, and any source you want to share with me will be happy.

+4
source share
1 answer

The difference between how the method filter()returns a list with items that match a specific condition. And the method takeWhile()also returns a list with elements that match a specific condition, but just take into account the first elements in the list.

An example for this:

val numbers = arrayOf(3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3)

println("*** takeWhile()")
println(numbers.takeWhile { it == 3 })
println("*** filter()")
println(numbers.filter { it -> it == 3 })

This will give you:

*** takeWhile()
[3, 3, 3]
*** filter()
[3, 3, 3, 3, 3, 3, 3]
+12
source

Source: https://habr.com/ru/post/1676948/


All Articles