Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply or condition in filter in scala?

Tags:

scala

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?

like image 516
Mahek Shah Avatar asked Dec 06 '22 20:12

Mahek Shah


2 Answers

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)
like image 200
dcastro Avatar answered Dec 28 '22 18:12

dcastro


Consider also a for comprehension as follows,

for (x <- a if x % 3 == 0 || x % 2 == 0) yield x
like image 42
elm Avatar answered Dec 28 '22 19:12

elm