Core Java

Java 8 Functional Interface – BiPredicate Example

Hello. In this tutorial, we will explain the BiPredicate functional interface in Java 8.

1. Introduction

java 8 BiPredicate

Java 8 BiPredicate functional interface represents a method that accepts two input arguments and returns a boolean output. Represented by the method syntax – boolean test(T t, U u). This interface also provides some default methods like –

  • default BiPredicate or(BiPredicate other) – Composed predicate that represents the Logical OR operation of one predicate and the other
  • default BiPredicate and(BiPredicate other) – Composed predicate that represents the Logical AND operation of one predicate and the other
  • default BiPredicate negate() – Returns a predicate that represents the logical negation of the given predicate

2. Practice

Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed in your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Model class

Create a java file in the com.jcg.model package and add the following code. The class will act as a model class for the creation of the student list.

Student.java

package com.jcg.model;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Student {

    private static final int BOUND = 100;
    private static final Random RANDOM = new Random();

    private final int id;
    private final String name;
    private final String department;

    private Student(int id, String name, String department) {
        this.id = id;
        this.name = name;
        this.department = department;
    }

    public static List<Student> create() {
        List<Student> students = new ArrayList<>();
        students.add(new Student(RANDOM.nextInt(BOUND), "adam", "medical"));
        students.add(new Student(RANDOM.nextInt(BOUND), "eve", "commerce"));
        students.add(new Student(RANDOM.nextInt(BOUND), "john", "non-medical"));
        students.add(new Student(RANDOM.nextInt(BOUND), "asha", "medical"));

        return students;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDepartment() {
        return department;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", department='" + department + '\'' +
                '}';
    }
}

2.2 Understanding the BiPredicate

Create a java file in the com.jcg package and add the following code. The class will show the BiPredicate functional interface implementation in different ways.

AppMain.java

package com.jcg;

import com.jcg.model.Student;

import java.util.List;
import java.util.function.BiPredicate;

/*
Java8 functional interface - BiPredicate
represents a boolean valued function of two arguments and returns a boolean value
method syntax - <code>boolean test(T t, U u);</code>
 */
public class AppMain {
    // method #1
    public static void method1() {
        BiPredicate<String, Integer> filterByLength = (str1, length) -> str1.length() >= length;

        boolean isEqual = filterByLength.test("adam", 5);
        System.out.println(isEqual);

        boolean isEqual1 = filterByLength.test("geek", 4);
        System.out.println(isEqual1);
    }

    // method #2
    public static void method2() {
        List<Student> students = Student.create();

        BiPredicate<Student, String> filterByDepartment =
                (student, department) -> student.getDepartment().equals(department);

        for (Student student : students) {
            boolean result = filterByDepartment.test(student, "medical");
            if (result)
                System.out.println(student);
        }
    }

    // method #3
    // returns a composed predicate that represents the logical AND of one predicate and another
    // method syntax - <code>default BiPredicate and(BiPredicate other)</code>
    // similarly we can also have a composed predicate that represents the logical OR
    public static void method3() {
        List<Student> students = Student.create();

        BiPredicate<Student, String> namePrefixFilter = (student, prefix) -> student.getName().startsWith(prefix);

        BiPredicate<Student, String> nameSuffixFilter = (student, suffix) -> student.getName().endsWith(suffix);

        for (Student student : students) {
            boolean result = namePrefixFilter.and(nameSuffixFilter).test(student, "a");
            if (result)
                System.out.println(student);
        }
    }

    // method #4
    // returns a predicate that represents logical negation of the given predicate
    // method syntax - <code>default BiPredicate negate()</code>
    public static void method4() {
        BiPredicate<String, Integer> filterByLength = (string, length) -> string.length() >= length;

        // string length should not greater than or equal to 5
        System.out.println(filterByLength.negate().test("geeks", 5));
    }

    public static void main(String[] args) {
        System.out.println("-- BiPredicate functional interface implementation --\n");
        method1();
        System.out.println("\n");
        method2();
        System.out.println("\n");
        method3();
        System.out.println("\n");
        method4();
    }
}

3. Code Run

Run the main file as a java application and if everything goes well the following output will be logged in the IDE console. You’re free to comment/uncomment the method for a better understanding of the BiPredicate functional interface.

Console output

-- BiPredicate functional interface implementation --

false
true


Student{id=92, name='adam', department='medical'}
Student{id=24, name='asha', department='medical'}


Student{id=92, name='asha', department='medical'}


false

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

4. Summary

In this tutorial, we learned the BiPredicate functional interface introduced in java8 programming along with the implementation. The interface is responsible to produce a boolean result after the evaluation of two input arguments. You can download the source code from the Downloads section.

5. Download the Project

This was a tutorial on learning and implementing the BiPredicate functional interface in java8 programming.

Download
You can download the full source code of this example here: Java 8 Functional Interface – BiPredicate Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button