I\'m trying to search a scala collection for an item in a list that matches some predicate. I don\'t necessarily need the return value, just testing if the list contains it.
Use filter:
scala> val collection = List(1,2,3,4,5)
collection: List[Int] = List(1, 2, 3, 4, 5)
// take only that values that both are even and greater than 3
scala> collection.filter(x => (x % 2 == 0) && (x > 3))
res1: List[Int] = List(4)
// you can return this in order to check that there such values
scala> res1.isEmpty
res2: Boolean = false
// now query for elements that definitely not in collection
scala> collection.filter(x => (x % 2 == 0) && (x > 5))
res3: List[Int] = List()
scala> res3.isEmpty
res4: Boolean = true
But if all you need is to check use exists
:
scala> collection.exists( x => x % 2 == 0 )
res6: Boolean = true