what's the best way to also capture what's filtered out in scala?

Viewed 26

Trivial example

List.range(1, 10).filter(_ % 2 == 0)

This will yield List(2,4,6,8). What's the best way to also get what was filtered out: List(1,3,5,7,9)

1 Answers

If you want to know both what passes some filter and what doesn't, instead of filter use partition:

val (even, odd) = List.range(1, 10).partition(_ % 2 == 0)
// even: List[Int] = List(2, 4, 6, 8)
// odd: List[Int] = List(1, 3, 5, 7, 9)
Related