Why is List.dropWhile not working?

This code:

val test = List(1, 2, 3)
printList[Int](test.dropWhile((a: Int) => {a == 1}))

And it will print correctly: 2 3 When using this code:

val test = List(1, 2, 3)
printList[Int](test.dropWhile((a: Int) => {a == 2}))

And it will print incorrectly: 1 2 3 And therefore a == 3 How to use dropWhileaccordingly?

Well, I realized that dropWhile returns "the longest suffix of this list, the first element of which does not satisfy the predicate p". Therefore, if I want some elements to satisfy the predicate p, I have to use filterNot :)

+4
source share
1 answer

This is because dropWhile

the longest prefix of elements that satisfy the predicate falls.

, , . , .

( , ) filterNot ( NOT, ):

val test = List(1, 2, 3)
printList[Int](test.filterNot((a: Int) => {a == 2}))

val test = List(1, 2, 3)
printList[Int](test.filter((a: Int) => {a != 2}))
+21

All Articles