Java Stream How to - Pass in method reference as Predicate








Question

We would like to know how to pass in method reference as Predicate.

Answer

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
//from  ww  w . j av  a  2s  .  c o  m
public class Main {
  public static void main(String[] args) {
    List<Person> persons = new ArrayList<Person>();
    persons.add(new Person("Peter", 65, Person.Gender.MALE));
    persons.add(new Person("Kevin", 5, Person.Gender.MALE));
    persons.add(new Person("Mandy", 19, Person.Gender.FEMALE));

    // Method Reference
    Collection<Person> eighteen = list(persons, (Person p) -> p.getAge() >= 18);
    System.out.println(eighteen);

    // Method Reference static
    Collection<Person> malePersons = list(persons, Person::isMale);
    System.out.println(malePersons);

    // Method Reference non static
    Person a = new Person("a", 1, Person.Gender.MALE);
    Collection<Person> femalePersons = list(persons, a::isFemale);
    System.out.println(femalePersons);
  }

  public static Collection<Person> list(Collection<Person> persons,
      PersonPredicate<Person> predicate) {
    List<Person> matchedPersons = new ArrayList<Person>();
    for (Person p : persons) {
      if (predicate.evaluate(p)) {
        matchedPersons.add(p);
      }
    }
    return matchedPersons;
  }
}
@FunctionalInterface
interface PersonPredicate<T> {
  boolean evaluate(T t);
}

class Person {
  public enum Gender {
    MALE, FEMALE
  }

  private String name;
  private int age;
  private Gender gender;

  public Person(String name, int age, Gender gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }

  public String getName() {
    return name;
  }

  public int getAge() {
    return age;
  }

  public Gender getGender() {
    return gender;
  }

  public String toString() {
    return getName() + ", " + getAge();
  }

  public static boolean isMale(Person p) {
    return Person.Gender.MALE.equals(p.getGender());
  }
  
  public boolean isFemale(Person p) {
    return Person.Gender.FEMALE.equals(p.getGender());
  }
}

The code above generates the following result.