Java Stream How to - Negate Predicate








Question

We would like to know how to negate Predicate.

Answer

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
/*from  w w  w.j ava2  s.  com*/
public class Main {
   public static void main(String[] args) {
      Predicate<Student> isPaidEnough = e -> e.gpa > 1;
      Predicate<Student> isExperiencedEnough = e -> e.id < 10;

      List<Student> students = Arrays.asList(
            new Student(1, 3, "John"),
            new Student(2, 4, "Jane"),
            new Student(3, 3, "Jack")
      );

      System.out.println(findStudents(students, isPaidEnough));
      System.out.println(findStudents(students, isExperiencedEnough));
      System.out.println(findStudents(students, isExperiencedEnough.negate()));

      Student somebody = students.get(0);
      System.out.println(findStudents(students, Predicate.<Student>isEqual(somebody)));
   }

   private static List<Student> findStudents(List<Student> employees, Predicate<Student> condition) {
      List<Student> result = new ArrayList<>();

      for (Student e : employees) {
         if (condition.test(e)) {
            result.add(e);
         }
      }

      return result;
   }


}
class Student {
      public int id;
      public long gpa;
      public String name;

      Student(int id, long g, String name) {
         this.id = id;
         this.gpa = g;
         this.name = name;
      }

      @Override
      public String toString() {
         return id + ">" + name + ": " + gpa;
      }
   }

The code above generates the following result.