Search code examples
javapredicate

Initalize and chain predicate


I have a person class as follows:

class Person {
       String sex;
       boolean mastersDegree;
       String position;
       //some more fields
       //getters, setters, const. toString ..
    }

I have to filter a list of persons without knowing the filter criteria before hand. I'll get those at run time through some boolean variables

boolean isMale = false;
boolean isDeveloper = false;
boolean hasMaster = true;

I want to use a predicate and chain them if needed according to the boolean values. Only true values should be used to create the filter predicate, i.e if all are false the list should not be filterd at all. For now I am doing it like

List<Person> persons = ...

Predicate<Person> filter = null;

if (isMale)
    filter = x -> x.getSex().equals("M");
if (isDeveloper)
    filter = filter.and(x -> x.getPosition().equals("DEV"));
if (hasMaster)
   filter = filter.and(Person::hasAMastersDegree);

persons.stream().filter(filter).forEach(System.out::println);

The above has one issue: it only works if the first if condition is met and I intialize the predicate with null first. Otherwise I will get a NPE or "variable filter might haven't been initialized". I have looked into the predicate class hoping to find some static value something like Predicate.TRUE which accepts every item or dosent filter at all but with no luck. I want to avoid this if possible:

if(isMale && filter != null)

How can I do so?

Predicate<Person> filter = ???;

Solution

  • You can initialise it with

    Predicate<Person> filter = p -> true;