我正在尝试在 scala 集合中搜索列表中与某些谓词匹配的项目。我不一定需要返回值,只是测试列表是否包含它。
在 Java 中,我可能会这样做:
for ( Object item : collection ) {
if ( condition1(item) && condition2(item) ) {
return true;
}
}
return false;
在 Groovy 中,我可以执行以下操作:
return collection.find { condition1(it) && condition2(it) } != null
在 Scala 中执行此操作的惯用方法是什么?我当然可以将 Java 循环样式转换为 Scala,但我觉得有一种更实用的方法可以做到这一点。
最佳答案
使用过滤器:
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
但如果您需要的只是检查使用存在
:
scala> collection.exists( x => x % 2 == 0 )
res6: Boolean = true
关于scala - 在 Scala 中查找与谓词匹配的项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9556579/