Search This Blog

Thursday 3 September 2015

Predicates to determine the truth !

We have seen some of the functional interfaces like Consumer and Supplier in the earlier posts. The next one I wanted to explore is the Predicate interface. This one is used for testing certain conditions on a passed instance and returns a boolean value.
Consider the User class below:
public class User {

   private String name;
   private int age;
   private double salary;
   //setter getters
}
I wanted to use predicates to decide if a user is eligible to vote:
public static boolean isEligibleToVote(User user) {
      return user.getAge() > 18;
   }
This logic could be wrapped into a Java object using Predicates
   static Predicate<User> userEligibleToVote = user -> user.getAge() > 18;

   public static boolean isEligibleToVote(User user) {
      return userEligibleToVote.test(user);
   }
As seen we wrapped the imperative style code into a Class.The Predicate interface also defines some easy methods to get other conditions created.
static Predicate<User> userEligibleToVote = user -> user.getAge() > 18;
   static Predicate<User> userNotEligibleToVote = userEligibleToVote.negate();
   
   static Predicate<User> unemployedUser = user -> user.salary <= 0;
   
   static Predicate<User> unemployedVoter = userEligibleToVote.and(unemployedUser);
   static Predicate<User> unemployedOrVoter = userEligibleToVote.or(unemployedUser);
As seen above, the negate method will create a predicate that is the exact negation of the passed predicate, the and method will combine two predicates to create a new predicate that returns the result by performing a boolean and between two predicates. Similarly or method will perform an or operation between tow predicates.
Predicates have been used in the Collection class. Consider the removeIf method below:
public void testRemoveIf(List<User> users) {
      int testAge = 24;
      System.out.println("Number of users : " + users.size());
      users.removeIf(user -> user.getAge() > testAge);
      System.out.println("Number of users with age < " + testAge + " : " + users.size());
   }
The compiler would be responsible for creating a predicate from the Lambda expression and then testing it on all the members of the passed collection. Those that pass it would be retained while the rest would be removed from it.

No comments:

Post a Comment