Java Predicate

  • A predicate is a functional interface with abstract method test()
    • boolean test(T t);
  • Represents a boolean value function i.e takes one argument and returns false
  • Can be used with lambda expression
    • Examples
      • Filtering a list of collections using stream
        • Stream<T> filter(Predicate<? super T> predicate);
  • Can be used instead of If else
  • Types of Predicate

Predicate is used in Stream filter

Predicate as a variable

Combining Predicates

Combining Predicates using and

Combining Predicates using or

Predicate with negate

Predicate as an argument to a utility stream

Predicate instead of If else

Creating Helper Class with Predicate

  • helper classes are classes that contain static functions to support a class
  • We can create functions using java 8 which accept a predicate i.e the function accept a logic instead of a variable or an object
  • Example Below
public class Hosting {

    private int Id;
    private String name;
    private String url;

    public Hosting(int id, String name, String url) {
        Id = id;
        this.name = name;
        this.url = url;
    }

    //... getters and setters, toString()
}
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class HostingRespository {

    public static List<Hosting> filterHosting(List<Hosting> hosting,
                                              Predicate<Hosting> predicate) {
        return hosting.stream()
                .filter(predicate)
                .collect(Collectors.toList());
    }

}

public class Java8Predicate7 {

    public static void main(String[] args) {

        Hosting h1 = new Hosting(1, "amazon", "aws.amazon.com");
        Hosting h2 = new Hosting(2, "linode", "linode.com");
        Hosting h3 = new Hosting(3, "liquidweb", "liquidweb.com");
        Hosting h4 = new Hosting(4, "google", "google.com");

        List<Hosting> list = Arrays.asList(new Hosting[]{h1, h2, h3, h4});

        List<Hosting> result = HostingRespository.filterHosting(list, x -> x.getName().startsWith("g"));
        System.out.println("result : " + result);  // google

        List<Hosting> result2 = HostingRespository.filterHosting(list, isDeveloperFriendly());
        System.out.println("result2 : " + result2); // linode

    }

    public static Predicate<Hosting> isDeveloperFriendly() {
        return n -> n.getName().equals("linode");
    }
}

Reference :

Leave a Comment