Java 8 : BiPredicate Functional Interface

BiPredicate

Similar to Predicate, a BiPredicate is used for filtering or matching and it returns a boolean value. However, it takes 2 arguments while Predicate takes 1 argument.


@FunctionalInterface public class BiPredicate<T, U> {

    void test(T t, U u); // Performs this operation on the given argument.
    
}

BiPredicate Example 1 :

Predicate<String> p1 = str -> str.isEmpty();
System.out.println(p1.test("TopJavaTutorial"));

BiPredicate<String,String> p2 = (str1,str2) -> str1.startsWith(str2);
System.out.println(p2.test("TopJavaTutorial","Top"));

Output :

false
true
 

BiPredicate Example 2 : BiPredicate with Method Reference

Predicate<String> p1 = String::isEmpty;
System.out.println(p1.test("TopJavaTutorial"));

BiPredicate<String,String> p2 = String::startsWith;
System.out.println(p2.test("TopJavaTutorial","Top"));

Output :

false
true
 

BiPredicate default methods

BiPredicate negate()

Returns a Predicate that is negation of the Predicate.

BiPredicate negate() example :

package com.topjavatutorial;

import java.util.function.BiPredicate;

public class TestBiPredicate {

  public static void main(String[] args) {
    BiPredicate<Integer, Integer> bi = (num1, num2) -> num1 > num2;
    System.out.println(bi.test(10, 5));
    System.out.println(bi.negate().test(10, 5));
  }
}

Output :

true
false
 
BiPredicate and()

Returns a Predicate that is logical AND of this predicate and another.

BiPredicate and() example :

package com.topjavatutorial;

import java.util.function.BiPredicate;

public class TestBiPredicate {

  public static void main(String[] args) {
    BiPredicate<Integer, Integer> biPredicate1 = (num1, num2) -> num1 > num2;
    BiPredicate<Integer, Integer> biPredicate2 = (num1, num2) -> num1 * num1 > num2 * num2;

    System.out.println(biPredicate1.test(10, 5));
    System.out.println(biPredicate1.test(10, 5));

    System.out.println(biPredicate1.and(biPredicate2).test(10, 5));
    System.out.println(biPredicate1.and(biPredicate2).test(-10, -5));
  }
}

Output :

true
true
true
false
 
BiPredicate or()

Returns a Predicate that is logical OR of this predicate and another.

BiPredicate or() example :

package com.topjavatutorial;

import java.util.function.BiPredicate;

public class TestBiPredicate {

  public static void main(String[] args) {
    BiPredicate<Integer, Integer> biPredicate1 = (num1, num2) -> num1 > num2;
    BiPredicate<Integer, Integer> biPredicate2 = (num1, num2) -> num1 * num1 > num2 * num2;

    System.out.println(biPredicate1.test(10, 5));
    System.out.println(biPredicate1.test(10, 5));

    System.out.println(biPredicate1.or(biPredicate2).test(10, 5));
    System.out.println(biPredicate1.or(biPredicate2).test(-10, -5));
  }
}

Output :

true
true
true
true
 

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags