Java 8 Predicate

By | | Updated : 2021-05-01 | Viewed : 123 times

Java 8 Predicate

The current tutorials show examples with good explanations for Java 8 Predicate. Some we need to write our conditions in functional interfaces. So predicate will help to write conditions where can be passed to the functional interfaces.

What Is Predicate In Java 8

The Predicate is a functional interface and can be passed as a conditional argument in a lambda expression. So filter provides the results based on Predicate. we will in detail explanation in given examples.

Predicate Examples with filter()

We will try to write the different types of predicates on different Tutorials. Please try to have a look at the below given example.

TutorialPredicates.java
public class TutorialPredicates {

    public static Predicate<Tutorial> isAuthorGood() {
        return t -> t.getRating() > 4;
    }

    public static Predicate<Tutorial> isTutorialLengthy() {
        return t -> t.getDuration() > 5;
    }
    public static List<Tutorial> filterTutorials (List<Tutorial> tutorials,
                                                  Predicate<Tutorial> predicate)
    {
        return tutorials.stream()
                .filter( predicate )
                .collect(Collectors.<Tutorial>toList());
    }
}

Here we have written two predicates one is the author is good or bad based on rating. The second one is trying to get the lengthy tutorials based on duration.

MainClient.javav
public class MainClient {

       public static void main(String[] args)
        {
            Tutorial tutorial1 = new Tutorial(1,"Java","James",8.3f,"Language", 4.5f);
            Tutorial tutorial2 = new Tutorial(2,"C++","Bjarne",6.3f,"Language", 3.5f);
            Tutorial tutorial3 = new Tutorial(3,"C","Dennis",4.3f,"Language", 4.6f);
            Tutorial tutorial4 = new Tutorial(4,"Python","Guido",4.3f,"Language", 3.6f);

            List<Tutorial> tutorials = new ArrayList<Tutorial>();
            tutorials.add(tutorial1);
            tutorials.add(tutorial2);
            tutorials.add(tutorial3);
            tutorials.add(tutorial4);

            System.out.println("Display popular tutorials");

            List<Tutorial> resultedTutorials = filterTutorials(tutorials, isAuthorGood());
            resultedTutorials.forEach(System.out::println);

            System.out.println("Display lengthy tutorials");

            List<Tutorial> resultedTutorials1 = filterTutorials(tutorials, isTutorialLengthy());
            resultedTutorials1.forEach(System.out::println);

        }

}

We tried to fetch the different types of types tutorials based on the conditional argument that is predicates passed in filter() methods. Please look at the below given example.

To get full code access you can refer to the GitHub repo Java8-Predicate-Example-App

Leave A Reply