Given code:
val test = List(1, 2, 3)
printList[Int](test.dropWhile((a: Int) => {a == 1}))
And it will print correctly: 2 3
While using code like this:
val test = List(1, 2, 3)
printList[Int](test.dropWhile((a: Int) => {a == 2}))
And it will print incorrectly: 1 2 3
And so does a == 3
How do I use dropWhile
appropriately?
well, I figure out that dropWhile return "the longest suffix of this list whose first element does not satisfy the predicate p." So if I want to detele some elements satisfy predicate p, I have to use filterNot : )
That's because dropWhile
drops longest prefix of elements that satisfy a predicate.
That is, it stops dropping as long as the condition is no longer met. In your second example it's not met from start, hence nothing is dropped.
You might be better off with a filter (which selects all elements satisfying a predicate) or filterNot (which selects all element NOT satisfying a predicate):
val test = List(1, 2, 3)
printList[Int](test.filterNot((a: Int) => {a == 2}))
or
val test = List(1, 2, 3)
printList[Int](test.filter((a: Int) => {a != 2}))
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