I have a list of Int
and I want to filter the list with the help of or statement.
For example :
var a = List(1,2,3,4,5,6)
I want to filter list based on _ % 3 == 0
or _ % 2 == 0
.
How can I do this?
a.filter(x => x % 3 == 0 || x % 2 == 0)
Note that, when you refer to a lambda's argument more than once in the expression body, you can no longer use the _
notation.
scala> val a = List(1,2,3,4,5,6)
a: List[Int] = List(1, 2, 3, 4, 5, 6)
scala> a.filter(x => x % 3 == 0 || x % 2 == 0)
res0: List[Int] = List(2, 3, 4, 6)
Consider also a for comprehension as follows,
for (x <- a if x % 3 == 0 || x % 2 == 0) yield x
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