val xs = Iterator
.from(1)
.dropWhile(_ % 2 != 0)
.takeWhile(_ < 10)
.toList
val ys = Iterator
.from(1)
.filter(_ % 2 == 0)
.takeWhile(_ < 10)
.toList
println(xs)
println(ys)
Output:
List(2, 3, 4, 5, 6, 7, 8, 9)
List(2, 4, 6, 8)
Why? I was expecting the same output from both.
dropWhile discards all the items at the start of a collection for which the condition is true. It stops discarding as soon as the first item fails the condition.
filter discards all the items throughout the collection where the condition is not true. It does not stop until the end of the collection.
In your case, dropWhile drops 1 but stops when it reaches 2 because the condition _ % 2 != 0 is false.
filter, on the other hand, drops all the values for which _ % 2 == 0 is false, which is all the odd values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With