在Scala中find与谓词相匹配的项目

我正在尝试search匹配某个谓词的列表中的某个项目的scala集合。 我不一定需要返回值,只是testing列表是否包含它。

在Java中,我可能会这样做:

for ( Object item : collection ) { if ( condition1(item) && condition2(item) ) { return true; } } return false; 

在Groovy中,我可以这样做:

 return collection.find { condition1(it) && condition2(it) } != null 

斯卡拉这样做的惯用方法是什么? 我当然可以将Java循环风格转换为Scala,但我觉得有一个更实用的方法来实现这一点。

使用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 

但是,如果你所需要的是检查使用exists

 scala> collection.exists( x => x % 2 == 0 ) res6: Boolean = true 

testing是否存在值匹配谓词

如果你只是想testing一个值是否存在,你可以用…. exists

 scala> val l=(1 to 4) toList l: List[Int] = List(1, 2, 3, 4) scala> l exists (_>5) res1: Boolean = false scala> l exists (_<2) res2: Boolean = true scala> l exists (a => a<2 || a>5) res3: Boolean = true 

其他方法(一些基于评论):

计数匹配元素

计算满足谓词的元素(并检查count> 0)

 scala> (l count (_ < 3)) > 0 res4: Boolean = true 

返回第一个匹配元素

find满足谓词的第一个元素(如Tomer Gabel和Luigi Plinge所build议的那样,这应该是更高效的,因为只要它find满足谓词的元素就返回,而不是遍历整个列表)

 scala> l find (_ < 3) res5: Option[Int] = Some(1) // also see if we found some element by // checking if the returned Option has a value in it scala> l.find(_ < 3) isDefined res6: Boolean = true 

testing是否存在确切的值

对于我们实际上只检查一个特定元素是否在列表中的简单情况

 scala> l contains 2 res7: Boolean = true