scala - 在 Scala 中查找与谓词匹配的项

标签 scala collections idioms

我正在尝试在 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/

相关文章:

scala - 有人可以分享 Odersky 在 2011 年 Scala 日的主题演讲中的 Coder 类的干净版本吗?

mysql - 将 monad 组合翻译成 SQL

java - 如何从同步映射java将映射条目添加到同步/非同步映射

scala - 基于列表长度的匹配模式匹配

scala - Scala协方差-现实生活中的例子

java - 过滤列表的最佳方法是什么?

c# - 对象数组/集合

c++ - 围绕两个范围的幂循环变量

c++ - 依赖最小化 C++

scala - Scalas Product.productIterator 应该做什么?