Search code examples
scalafunctional-programmingpredicate

Chaining multiple predicates for filter in scala


I am new to functional programming. I want to chain multiple predicates for filter.

Suppose I have list of names which i want to filter with...

 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")
  })

How to make the above line dynamic,so that I dont have to write it. Iwant to create it according to the list of names user provides.


Solution

  • You can use exists to check if some predicate is fulfilled for any value in a collection (OR on predicate at every element) or forall to check if predicate id filfilled for all values (AND on predicate at every element).

    You could use it for example like this:

    val names = List("cat", "dog", "elephant")
    val predicate = (s: String) => names.exists(s.endsWith _)
    objects.filter(predicate)