Guava Predicate Tutorial

We will be examining several use cases for Guava Predicates. Guava Predicates provide a way to quickly and efficiently filter and transform collections based upon some sort of criteria.

To create a predicate, you can create a class that implements the Predicate<T> interface. Classes which implement the Predicate<T> interface must override and implement a single method.


boolean apply(T input)

Lets say you are maintaining a book store catalog with various books and would like to quickly filter your collection based upon the copyright year of the book. First let’s create a Book class.


public class Book
{

   private String myTitle;

   private String myAuthor;

   private int myCopyrightYear;

   public(String title, String author, int copyrightYear)
   {
      myTitle = title;
      myAuthor = author;
      myCopyrightYear = copyrightYear;
   }

   public String getTitle()
   {
      return myTitle;
   }

   public String getAuthor()
   {
      return myAuthor;
   }
   
   public int getCopyrightYear()
   {
      return myCopyrightYear;
   }
 
   @Override
   public String toString()
   {
      return myTitle + " by " + myAuthor + ", Copyright " + myCopyrightYear;

   }
}

Now that we have a class to store our book information, let’s create a Predicate that allows us to filter our books by copyright year.


import com.google.common.base.Precicate;

public class FilterByCopyrightYear implements Predicate
{
   private int myCopyrightYear;

   public FilterByCopyrightYear(int copyrightYear)
   {
      myCopyrightYear = copyrightYear;
   }

   @Override
   public boolean apply(Book book)
   {
      if(book.getCopyrightYear() != myCopyrightYear)
      {
         return false;
      }

      return true;
   } 
}

Now that we have our predicate, let’s put together an example to show how easy it is to filter a collection of books based upon copyright year.


public class FilterByPredicate 
{
   public static main(String[] args)
   {
      // Guava also provides the Lists.newArrayList(...) method to quickly create a list.
      List books = Lists.newArrayList(
         new Book("Fantastic Voyage", "Me", 2000),
         new Book b1 = new Book("Coding is Cool!", "You", 2017),
         new Book b2 = new Book("Software for Fools!", "Bob", 2018));
 
      Predicate booksIn2017 = new Predicate<>(2017);
      
      // The Guava Collections2 class allows us to apply a filter using a Collection and Predicate.
      Collection filteredBooks = Collections2.filter(books, booksIn2017);

      // Should print out "Coding is Cool! by You, Copyright 2017"
      System.out.println(filteredBooks);

   }
}

This just scratches the surface of the power of predicates. Predicates can be much more complicated than shown in this basic example. They can also be chained together to create much more complex filters than shown above.