我对函数式编程很陌生。我想为过滤器链接多个谓词。
假设我有要过滤的名字列表.
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")
})
如何使上面的行动态,这样我就不用写了。根据用户提供的名称列表创建它。
发布于 2020-06-05 09:07:30
您可以使用exists
检查集合中的任何值是否实现了某个谓词(在每个元素上都有谓词),或者使用forall
检查是否为所有值(以及每个元素上的谓词)填充了谓词id。
您可以使用它,例如:
val names = List("cat", "dog", "elephant")
val predicate = (s: String) => names.exists(s.endsWith _)
objects.filter(predicate)
发布于 2020-06-05 09:07:23
您可以使用exists
来检查动态列表names
是否有这样的值。
val names = List("cat","dog","elephant")
val objects = List("stringcat", "dog", "dognot")
objects.filter(string => {
names.exists(n => string.endsWith(n))
})
// List(stringcat, dog)
https://stackoverflow.com/questions/62211682
复制相似问题