scala - 在scala中为过滤器链接多个谓词
问题描述
我是函数式编程的新手。我想为过滤器链接多个谓词。
假设我有要过滤的名称列表...
val names = List("cat","dog","elephant")
//Currently I am doing like this, this is not dynamic,The list of name will come dynamically
objects.filterSubjects(string => {
string.endsWith("cat") || string.endsWith("dog") || string.endsWith("elephant")
})
如何使上面的行动态化,这样我就不用写了。我想根据用户提供的名称列表创建它。
解决方案
您可以使用exists
来检查集合中的任何值是否满足某个谓词(或每个元素的谓词)或forall
检查所有值是否满足谓词 id(每个元素的谓词)。
例如,您可以像这样使用它:
val names = List("cat", "dog", "elephant")
val predicate = (s: String) => names.exists(s.endsWith _)
objects.filter(predicate)
推荐阅读
- javascript - 如何自定义chartjs
- python - Amazon lex 错误 - 发生错误:无效的 Lambda 响应:收到来自 Lambda 的错误响应:未处理
- node.js - MERN 堆栈身份验证结构
- flutter - Flutter - 如何创建这些自定义容器形状?
- gradle - 无法将 gradle wrapper 从版本 2.1 升级到 6.5.1
- encoding - 将二进制数据编码为 ASCII,同时保留其大部分有效字符
- javascript - 当我从 JavaScript 中的数组中单击时如何获取该按钮的特定数组
- javascript - 为什么使用 Vue.js 时 Firebase 实时数据库中的数据仅在控制台中呈现,而不在页面上呈现?
- sql - 如何将 TIMESTAMP WITH TIMEZONE 转换为 TIMESTAMP 但在 SQL 中保持本地时间
- javascript - vuejs 制作对象数据数组