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.
In Java, I might do something like:
for ( Object item : collection ) {
if ( condition1(item) && condition2(item) ) {
return true;
}
}
return false;
In Groovy, I can do something like:
return collection.find { condition1(it) && condition2(it) } != null
What's the idiomatic way to do this in Scala? I could of course convert the Java loop style to Scala, but I feel like there's a more functional way to do this.
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