Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala dropWhile vs filter

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.

like image 403
Abhijit Sarkar Avatar asked Sep 11 '26 08:09

Abhijit Sarkar


1 Answers

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.

like image 115
Tim Avatar answered Sep 14 '26 15:09

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!