BiPredicate Functional Interface Java Examples

In this post we’ll see examples of java.util.function.BiPredicate functional interface.

BiPredicate functional interface represents a boolean valued function that takes two arguments and returns either true or false. Abstract method in this functional interface is-

test(T t, U u)- This method evaluates the predicate on the passed arguments and returns either true or false based on whether the input arguments match the predicate or not.

If you are writing a Lambda expression that takes two arguments and uses those arguments to evaluate a condition that returns true or false then that lambda expression can be written as an implementation of BiPredicate built-in functional interface.

Apart from the test(T t, U u) abstract method Predicate interface has following default interface methods.

  • and(BiPredicate<? super T,? super U> other)- This default method returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.
  • or(BiPredicate<? super T,? super U> other)- This default method returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.
  • negate()- This default method returns a predicate that represents the logical negation (reverse condition) of the passed predicate.

BiPredicate interface test() method example

import java.util.function.BiPredicate;

public class BiPredicateExample {
  public static void main(String[] args) {
    BiPredicate<String, String> bp = (s1, s2) -> s1.equals(s2);  
    boolean val = bp.test("knpcode.com", "knpcode.com");
    System.out.println("val is- " + val);
    val = bp.test("Hello", "Test");
    System.out.println("val is- " + val);
  }
}
Output
val is- true
val is- false

In the example this lamdba expression- BiPredicate<String, String> bp = (s1, s2) -> s1.equals(s2); is the implementation of BiPredicate interface. When test() method with two arguments is called Java can infer from the context that lambda expression is the implementation of test() method.

2. In the second example we’ll write a method that takes BiPredicate as a method argument. Method checks whether the file at the given path is a regular file or a directory.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.function.BiPredicate;

public class BiPredicateExample {
  public static void main(String[] args) throws IOException {
    // Called with directory - returns false
    Path path = Paths.get("F:\\knpcode\\Parent");
    System.out.println(isFile(path, (p, fileAttributes) -> fileAttributes.isRegularFile()));
    // Called with File - returns false
    path = Paths.get("F:\\knpcode\\Parent\\Test.txt");
    System.out.println(isFile(path, (p, fileAttributes) -> fileAttributes.isRegularFile()));
  }
	
  private static boolean isFile(Path path, BiPredicate<Path, BasicFileAttributes> matcher) throws IOException {
    return matcher.test(path, Files.readAttributes(path, BasicFileAttributes.class));
  }
}
Output
false
true

BiPredicate functional interface in JDK

These built-in functional interfaces are used extensively by the Java language itself. You can fine the usage of BiPredicate functional interface in Files.find() method.

Stream<Path> find(Path start, int maxDepth, BiPredicate<Path,BasicFileAttributes> matcher, FileVisitOption... options)- This method returns a Stream that is lazily populated with Path by searching for files in the given path. Files that will be included in the stream is determined by the passed BiPredicate.

Here is an example that lists all the files in the passed directory and its child directories upto the depth of 10.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class BiPredicateExample {
  public static void main(String[] args) throws IOException {
    Path startPath = Paths.get("F:\\knpcode\\Parent");
    Stream<Path> fileStream = Files.find(startPath, 10, (path, fileAttributes) -> fileAttributes.isRegularFile());
    fileStream.forEach(System.out::println);
    fileStream.close();
  }
}

That's all for the topic BiPredicate Functional Interface Java Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Predicate Functional Interface Java Examples

In this post we’ll see examples of java.util.function.Predicate functional interface.

Methods in Predicate interface

Predicate functional interface represents a boolean valued function returning either true or false. Abstract method in this functional interface is-

boolean test(T t)- This method evaluates the predicate on the passed argument and returns either true or false based on whether the input argument matches the predicate or not.

If you are writing a Lambda expression that takes single argument and uses that argument to evaluate a condition that returns true or false then that lambda expression can be written as an implementation of Predicate built-in functional interface.

Apart from the test() abstract method Predicate interface has following default and static methods.

  • and(Predicate<? super T> other)- It is a default interface method that returns a composed predicate representing a short-circuiting logical AND of this predicate and another. First the calling Predicate is evaluated if that is false then the predicate passed as argument is not even evaluated.
  • or(Predicate<? super T> other)- It is a default method that returns a composed predicate representing a short-circuiting logical OR of this predicate and another. In the composed predicate first the calling Predicate is evaluated if that is true then the predicate passed as argument is not even evaluated.
  • negate()- It is a default method that returns a predicate representing the logical negation of this predicate.
  • isEqual(Object targetRef)- It is a static interface method returning a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).

Predicate interface test() method example

1. A simple implementation that checks if the passed argument is greater than 10 or not.

import java.util.function.Predicate;

public class PredicateExample {
  public static void main(String[] args) {
    Predicate<Integer> predicate = (i) -> i > 10;
    
    boolean val = predicate.test(8);
    System.out.println("val- " + val);
    
    val = predicate.test(15);
    System.out.println("val- " + val);
  }
}
Output
val- false
val- true

In the example; statement- Predicate predicate = (i) -> i > 10; is the implementation of Predicate interface as a lambda expression.

When predicate.test() method is called Java can infer from the context that lambda expression is the implementation of test() method.

2. In this example there is a method that takes two arguments; a Predicate and a List. From the passed list those elements that pass the predicate are added in another list.

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;

public class PredicateExample {	
  public static void main(String[] args) {
    List<Integer> myList = new ArrayList<Integer>();
    myList.add(20);
    myList.add(60);
    myList.add(40);
    myList.add(80);
            
    Collection<Integer> values = filter(n -> n > 50, myList);                
    System.out.println("Values in new list " + values);
  }
	
  public static <T> Collection<T> filter(Predicate<T> predicate, Collection<T> listItems) {
    Collection<T> newList = new ArrayList<T>();
    for(T item: listItems) {
      if(predicate.test(item)) {
        newList.add(item);
      }
    }
    return newList;
  }
}
Output
Values in new list [60, 80]

Predicate functional interface and() method example

In the example we’ll have a range check that the passed integer is greater than 10 but less than 30. This can be done using the and() method of the Predicate interface by creating two predicates and composing them using and() so that first greater than 10 condition is evaluated and then less than 30 condition is evaluated.

public class PredicateExample {
	
  public static void main(String[] args) {
    Predicate<Integer> predicate = (i) -> i > 10;
    Predicate<Integer> andPredicate = predicate.and((i) -> i < 30);
    
    boolean val = andPredicate.test(20);
    System.out.println("val is- " + val);
    
    val = andPredicate.test(40);
    System.out.println("val is- " + val);
    
    val = andPredicate.test(5);
    System.out.println("val is- " + val);
  }
}
Output
val is- true
val is- false
val is- false

Predicate functional interface or() method example

If you have a scenario where you want to check whether the passed string starts with letter ‘A’ or ‘B’ then you can use or() method of the Predicate interface to implement that logic.

public class PredicateExample {
	
  public static void main(String[] args) {
    Predicate<String> predicate = (s) -> s.toUpperCase().startsWith("A");
    Predicate<String> orPredicate = predicate.or((s) -> s.toUpperCase().startsWith("B"));
    
    boolean val = orPredicate.test("again");
    System.out.println("val is- " + val);
    
    val = orPredicate.test("Bat");
    System.out.println("val is- " + val);
    
    val = orPredicate.test("Dog");
    System.out.println("val is- " + val);
  }
}
Output
val is- true
val is- true
val is- false

Predicate functional interface negate() method example

Suppose you already have a Predicate that checks whether the passed String starts with A or not. Now you need to check the condition if the passed String starts with any other letter but A then you can negate the existing predicate to get the predicate that can check that.

public class PredicateExample {
	
  public static void main(String[] args) {
    Predicate<String> predicate = (s) -> s.toUpperCase().startsWith("A");
    Predicate<String> predicateNegate = predicate.negate();
    
    boolean val = predicateNegate.test("again");
    System.out.println("val is- " + val);
    
    val = predicateNegate.test("Bat");
    System.out.println("val is- " + val);
    
    val = predicateNegate.test("Dog");
    System.out.println("val is- " + val);
  }
}
Output
val is- false
val is- true
val is- true

Predicate functional interface in JDK

These built-in functional interfaces are used extensively with in the JDK itself. A very good example of usage of Predicate interface is filter() method of Stream interface in Java Stream API.

filter(Predicate<? super T> predicate)- Returns a stream consisting of the elements of this stream that match the given predicate.

Example where a List was filtered to create a new List can be rewritten using the filter() method of the Stream.

public class PredicateExample {
	
  public static void main(String[] args) {
    List<Integer> myList = new ArrayList<Integer>();
    myList.add(20);
    myList.add(60);
    myList.add(40);
    myList.add(80);
    List<Integer> newList = myList.stream().filter((i) -> i > 50).collect(Collectors.toList());
    newList.forEach(System.out::println);
  }
}
Output
60
80

That's all for the topic Predicate Functional Interface Java Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

BiFunction Functional Interface Java Examples

In this post we’ll see examples of java.util.function.BiFunction functional interface.

BiFunction functional interface represents an operation that accepts two arguments and produces a result. Abstract method in this functional interface is-

R apply(T t, U u)- Where t is the first argument, u is the second function argument and R denotes the type of the result that is returned.

If you are writing a Lambda expression that takes two arguments of same or different types and returns a value of another type then that lambda expression can be written as an implementation of BiFunction built-in functional interface.

Apart from the apply() abstract method Function() interface has following default interface method.

andThen(Function<? super R,? extends V> after)- It takes another Function as argument and returns a composed BiFunction that performs, in sequence, first the operation of the calling BiFunction followed by the after operation.

BiFunction interface apply() method example

1. Writing a function that takes two Strings as arguments and returns concatenated String as result.

import java.util.function.BiFunction;

public class BiFunctionExample {
  public static void main(String[] args) {
    BiFunction<String, String, String> ref = (str1, str2) -> str1+ " " +str2;
    System.out.println("Concatenated Strings- " + ref.apply("Hello", "Lambda"));
  }
}
Output
Concatenated Strings- Hello Lambda

2. Writing a function that takes two Integers (i1, i2) as argument and returns a double value which is i1 to the power i2.

public class BiFunctionExample {
  public static void main(String[] args) {
    BiFunction<Integer, Integer, Double> biFunction = (i1, i2) -> Math.pow(i1, i2);
    System.out.println("Result- " + biFunction.apply(3, 4));
  }
}
Output
Result- 81.0

BiFunction functional interface andThen() method example

In the example there will be a BiFunction interface and a Function interface, on the BiFunction, andThen() is called with Function as an argument. When apply() method is called on the BiFunction it first executes the BiFunction implementation and then the Function implementation.

public class BiFunctionExample {
  public static void main(String[] args) {
    BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;
    Function<Integer, Integer> function = (a) -> a * a;
    // Sequence First BiFunction then Function
    System.out.println("Result- " + biFunction.andThen(function).apply(3, 5));
  }
}
Output
Result- 64

BiFunction functional interface in JDK

These built-in functional interfaces are used extensively with in the JDK itself. In Map interface compute, computeIfPresent, computeIfPresent methods are added in Java8 out of these methods compute and computeIfPresent take BiFunction as argument.

computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)- If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

ComputeIfPresent example
public class BiFunctionExample {
  public static void main(String[] args) {
      Map<String, Integer> numMap = new HashMap<String, Integer>();
      numMap.put("A", 1);
      numMap.put("B", 3);
      numMap.put("C", 8);
      numMap.put("D", 5);
      System.out.println("------- Before Computation -------");
      numMap.forEach((key, val)-> System.out.println("Key- " +key + "Val- " + val));
      numMap.computeIfPresent("B", (key, val)-> val + 1);
      System.out.println("------- After Computation -------");
      numMap.forEach((key, val)-> System.out.println("Key- " +key + "Val- " + val));
  }
}
Output
------- Before Computation -------
Key- AVal- 1
Key- BVal- 3
Key- CVal- 8
Key- DVal- 5
------- After Computation -------
Key- AVal- 1
Key- BVal- 4
Key- CVal- 8
Key- DVal- 5

That's all for the topic BiFunction Functional Interface Java Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Function Functional Interface Java Examples

In this post we’ll see examples of java.util.function.Function functional interface.

Function functional interface represents an operation that accepts one argument and produces a result. Abstract method in this functional interface is-

R apply(T t)- Here T is the type of the argument passed to the method and it returns a value of type R.

If you are writing a Lambda expression that takes single argument of one type and returns a value of another type (or even same type) then that lambda expression can be written as an implementation of Function built-in functional interface.

Apart from the apply() abstract method Function() interface has following default and static methods.

  • andThen(Function<? super R, ? extends V> after)- It is a default method which takes another Function as argument and returns a composed Function that performs, in sequence, first the operation of the calling Function followed by the after operation.
  • compose(Function<? super V, ? extends T> before)- It is a default method in Function interface which takes another Function as argument and returns a composed Function that performs, in sequence, first the before operation then the operation of the calling Function.
  • identity()- It is a static method that returns a function which returns its input argument.

Function interface apply() method example

1. Writing a function that returns the length of the passed string.

public class FunctionExample {
  public static void main(String[] args) {
    Function<String, Integer> function = (s) -> s.length();
    System.out.println("Length- " + function.apply("Test"));
    System.out.println("Length- " + function.apply("Retrospective"));
  }
}
Output
Length- 4
Length- 13

In the example statement- Function<String, Integer> function = (s) -> s.length(); is the implementation of Function interface as a lambda expression.

When function.apply() method is called Java can infer from the context that lambda expression is the implementation of apply() method.

2. Finding factorial of a number as a lambda expression can be implemented as an instance of Function interface where input argument is an Integer and return value is of type Double.

import java.util.function.Function;

public class FunctionExample {
  public static void main(String[] args) {
    double result = factorial(10);
    System.out.println("Factorial- " + result);

  }

  public static double factorial(int n) {
    Function<Integer, Double> function =  x -> (x == 0) ? 1 : x * factorial(x - 1);
    return function.apply(n);
  }
}
Output
Factorial- 3628800.0

3. In this Function interface Java example a List of Employees is mapped to a list of names.

public class Employee {
  private String name;
  private String dept;
  private int salary;

  Employee(String name, String dept, int salary){
    this.name = name;
    this.dept = dept;
    this.salary = salary;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getSalary() {
    return salary;
  }
  public void setSalary(int salary) {
    this.salary = salary;
  }
  public String getDept() {
    return dept;
  }
  public void setDept(String dept) {
    this.dept = dept;
  }
}
public class FunctionExample {
  public static void main(String[] args) {
    List<Employee> employeeList = new ArrayList<>(); 

    employeeList.add(new Employee("Jack", "Finance", 5500)); 
    employeeList.add(new Employee("Lisa", "Finance", 5600)); 
    employeeList.add(new Employee("Scott", "Finance", 7000));
    employeeList.add(new Employee("Nikita", "IT", 4500));
    employeeList.add(new Employee("Tony", "IT", 8000));
    
    List<String> nameList = mapTo(employeeList, (e)->e.getName());
    nameList.forEach(System.out::println);
  }

  public static List<String> mapTo(List<Employee> empList, Function<Employee, String>mapper){
    List<String> nameList = new ArrayList<>();
    for(Employee emp : empList) {
      nameList.add(mapper.apply(emp));
    }
    return nameList;
  }
}
Output
Jack
Lisa
Scott
Nikita
Tony

In the example implementation of the Function is passed as the method argument-

mapTo(employeeList, (e)->e.getName());

Function functional interface andThen() method example

In the example there will be two Function interfaces, on the first Function, andThen() is called with second Function as an argument. Now, when apply() method is called on the second Function interface, it first executes the first Function implementation and then the second one.

We’ll use the previous example of Employee list, in first function interface we’ll get the salary of the Employee and then in the second function increase it by 10%.

public class FunctionExample {
  public static void main(String[] args) {
    int fin, it;
    List<Employee> employeeList = new ArrayList<>(); 
    employeeList.add(new Employee("Jack", "Finance", 5500)); 
    employeeList.add(new Employee("Lisa", "Finance", 5600)); 
    employeeList.add(new Employee("Scott", "Finance", 7000));
    employeeList.add(new Employee("Nikita", "IT", 4500));
    employeeList.add(new Employee("Tony", "IT", 8000));
    Function<Employee, Integer> function = (e)->e.getSalary();
    Function<Integer, Integer> functionAnother =  (Integer i)-> i + ((i * 10)/100);
    List<Integer> salaryList = mapTo(employeeList, function.andThen(functionAnother));
    salaryList.forEach(System.out::println);
  }

  public static List<Integer> mapTo(List<Employee> empList, Function<Employee, Integer>mapper){
    List<Integer> salaryList = new ArrayList<>();
    for(Employee emp : empList) {
      salaryList.add(mapper.apply(emp));
    }
    return salaryList;
  }
}
Output
6050
6160
7700
4950
8800

Function functional interface compose() method example

compose() is reverse of andThen() first the Second Function interface implementation is called then the first one.

In the previous andThen() example if compose method is called on the second function and as argument first function interface is passed we’ll have the same result as the previous example.

List<Integer> salaryList = mapTo(employeeList, functionAnother.compose(function));

Function functional interface in JDK

These built-in functional interfaces are used extensively with in the JDK itself. A very good example of usage of Function interface is map() method of Stream interface in Java Stream API.

map(Function<? superT,? extends R>mapper)- Returns a stream consisting of the results of applying the given function to the elements of this stream.

The example where we mapped Employee object list to a List of employee names, can be written using map() method of Stream.

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FunctionExample {
  public static void main(String[] args) {
    int fin, it;
    List<Employee> employeeList = new ArrayList<>(); 
    employeeList.add(new Employee("Jack", "Finance", 5500)); 
    employeeList.add(new Employee("Lisa", "Finance", 5600)); 
    employeeList.add(new Employee("Scott", "Finance", 7000));
    employeeList.add(new Employee("Nikita", "IT", 4500));
    employeeList.add(new Employee("Tony", "IT", 8000));
    // map to name and then collect to a list
    List<String> nameList = employeeList.stream().map((e)->e.getName()).collect(Collectors.toList());
    nameList.forEach(System.out::println);
  }
}
Output
Jack
Lisa
Scott
Nikita
Tony

That's all for the topic Function Functional Interface Java Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Supplier Functional Interface Java Examples

In this post we’ll see examples of java.util.function.Supplier functional interface.

Supplier functional interface represents an operation that accepts no argument and supplies a result. In Supplier interface there is one abstract method get() and there is no default or static interface method.

If you are writing a Lambda expression that needs a value returned then that lambda expression can be written as an implementation of Supplier built-in functional interface.

Supplier functional interface examples

1. If you want some random number to be generated, that can be implemented as get() method of Supplier interface.

import java.util.function.Supplier;

public class SupplierExample {
  public static void main(String[] args) {
    Supplier<Double> randomNoGen = () -> Math.random();
    System.out.println(randomNoGen.get());
    System.out.println(randomNoGen.get());
  }
}
Output
0.9507895772946557
0.11609076109430083

In the program statement; Supplier randomNoGen = () -> Math.random(); is the implementation of Supplier as a lambda expression. Since this implementation is an instance of a functional interface so assigned to variable of type Supplier.

When randomNoGen.get() method is called Java can infer from the context, due to “target typing”, where to look for the implementation of get() method.

2. If you want current date at several places in your application, you can implement it as a Supplier.

import java.time.LocalDate;
import java.util.function.Supplier;

public class SupplierExample {
  public static void main(String[] args) {
    Supplier<LocalDate> currDate = () -> LocalDate.now();
    System.out.println(currDate.get());
  }
}

3. Using it as a supplier of class object. If there is a class Employee then you can create objects of this class using Supplier interface.

public class Employee {
  private String name;
  private String dept;
  private int salary;
  Employee(){};
  Employee(String name, String dept, int salary){
    this.name = name;
    this.dept = dept;
    this.salary = salary;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getSalary() {
    return salary;
  }
  public void setSalary(int salary) {
    this.salary = salary;
  }
  public String getDept() {
    return dept;
  }
  public void setDept(String dept) {
    this.dept = dept;
  }
  @Override
  public String toString() {
    // TODO Auto-generated method stub
    return getName() + " " + getDept() + " " + getSalary();
  }
}
public class SupplierExample {
  public static void main(String[] args) {	
    // Invokes no-arg constructor
    Employee emp = getEmpObject(Employee::new);
    System.out.println(emp);
    // Invokes constructor with parameters
    emp = getEmpObject(() -> new Employee("David", "IT", 12000));
    System.out.println(emp);
  }

  public static Employee getEmpObject(Supplier<Employee> sup) {
    return sup.get();
  }
}

Supplier functional interface in JDK

Built-in functional interfaces are used extensively with in the JDK itself. In the Java Stream API there is a method generate() that takes Supplier as an argument.

generate(Supplier<T> s)- Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.

We can use this method to generate a stream of random numbers.

public class SupplierExample {
  public static void main(String[] args) {	
    Stream.generate(()->Math.random()).limit(3).forEach(System.out::println);
  }
}
Output
0.17411307331904347
0.9293020926865666
0.9854950033297908

That's all for the topic Supplier Functional Interface Java Example. If something is missing or you have something to share about the topic please write a comment.


You may also like

BiConsumer Functional Interface Java Examples

In this post we’ll see examples of Java BiConsumer functional interface.

BiConsumer functional interface represents an operation that accepts two arguments and returns no result. Abstract method in this functional interface is accept(T t, U u) and there is also one default method andThen(BiConsumer<? super T,? super U> after).

If you are writing a Lambda expression that needs two arguments and doesn’t return a value then that lambda expression can be written as an implementation of BiConsumer built-in functional interface.

BiConsumer functional interface example

1. In the example a Map is created and then entries of the Map are displayed. We’ll use lambda expression that implements the BiConsumer functional interface. Lambda expression you write implements the abstract method of the functional interface so in the case of BiConsumer functional interface, lambda expression is implementing the accept() method.

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

public class BiConsumerExample {
  public static void main(String[] args) {
    // Implementation
    BiConsumer<String, String> biCons = (K, V) -> 
          System.out.println("Key is- " +K + " Value is- " + V);
    Map<String, String> numMap = new HashMap<String, String>();
    numMap.put("1", "One");
    numMap.put("2", "Two");
    numMap.put("3", "Three");
    numMap.put("4", "Four");
    for(Map.Entry<String, String> entry : numMap.entrySet()) {
      // calling accept method
      biCons.accept(entry.getKey(), entry.getValue());
    }
  }
}
Output
Key is- 1 Value is- One
Key is- 2 Value is- Two
Key is- 3 Value is- Three
Key is- 4 Value is- Four

In the program, statement BiConsumer<String, String> biCons = (K, V) -> System.out.println("Key is- " +K + " Value is- " + V); is the implementation of BiConsumer as a lambda expression. Since it is an instance of a functional interface so assigned to variable of type BiConsumer.

Lambda supports "target typing" which infers the object type from the context in which it is used. When biCons.accept() method is called Java can infer from the context where to look for the implementation of accept() method.

2. Here is another example where add() and multiply() methods are implemented using BiConsumer interface.

public class BiConsumerExample {
  public static void main(String[] args) {
    // Implementation as add method
    BiConsumer<Integer, Integer> biConsAdd = (a, b) -> 
          System.out.println("Sum is- " + (a + b));
    // Implementation as multiplication method
    BiConsumer<Integer, Integer> biConsMul = (a, b) -> 
          System.out.println("Multiplication is- " + (a * b));

    biConsAdd.accept(5, 6);
    biConsMul.accept(5, 6);
  }
}
Output
Sum is- 11
Multiplication is- 30

BiConsumer functional interface andThen() method example

There is also a default method andThen() in BiConsumer interface.

BiConsumer<T,U> andThen(BiConsumer<? super T,? super U> after)- Takes another BiConsumer as argument and returns a composed BiConsumer that performs, in sequence, first the operation of the calling BiConsumer followed by the after operation.

In the previous example addition and multiplication are called in sequence for the same set of arguments. If that is the case then it can use the andThen() method.

public class BiConsumerExample {
  public static void main(String[] args) {
    // Implementation as add method
    BiConsumer<Integer, Integer> biConsAdd = (a, b) -> 
          System.out.println("Sum is- " + (a + b));
    // Implementation as multiplication method
    BiConsumer<Integer, Integer> biConsMul = (a, b) -> 
          System.out.println("Multiplication is- " + (a * b));
    //First add then multiply in sequence			
    biConsAdd.andThen(biConsMul).accept(5, 6);

    //biConsAdd.accept(5, 6);
    //biConsMul.accept(5, 6);
  }
}
Output
Sum is- 11
Multiplication is- 30

BiConsumer functional interface in JDK

These built-in functional interfaces are used extensively with in the JDK itself. One example of BiConsumer functional interface used quite often is when forEach() method is used to iterate a Map. In the Map interface there is a forEach() method that takes BiConsumer as an argument.

forEach(BiConsumer<? super K,? super V> action)- Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

First example where we iterated a Map can be written more concisely using forEach().

public class BiConsumerExample {
  public static void main(String[] args) {
    Map<String, String> numMap = new HashMap<String, String>();
    numMap.put("1", "One");
    numMap.put("2", "Two");
    numMap.put("3", "Three");
    numMap.put("4", "Four");
    numMap.forEach( (K, V) -> System.out.println("Key is- " + K + " Value is- " + V));
  }
}
Output
Key is- 1 Value is- One
Key is- 2 Value is- Two
Key is- 3 Value is- Three
Key is- 4 Value is- Four

That's all for the topic BiConsumer Functional Interface Java Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Java Consumer Functional Interface Examples

In this post we’ll see examples of Java Consumer functional interface which is one of the built-in functional interface.

Consumer functional interface represents an operation that accepts a single argument and returns no result. Abstract method in this functional interface is accept(T t) and there is also one default method andThen().

Consumer functional interface example

In the example a List of integer is created and then elements of the List are displayed.

we’ll use lambda expression that implements the Consumer functional interface. Lambda expression you write implements the abstract method of the functional interface so in the case of Consumer functional interface, lambda expression is implementing the accept() method.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerExample {
  public static void main(String[] args) {
    Consumer<Integer> consumer = i -> System.out.println(i);
    List<Integer> numList = Arrays.asList(1, 2, 3, 4);
    for(Integer i : numList) {
      consumer.accept(i);
    }
  }
}
Output
1
2
3
4

Here this statement Consumer<Integer> consumer = i -> System.out.println(i + " "); is the implementation of Consumer as a lambda expression. Since the implementation is an instance of a functional interface so assigned to variable of type Consumer.

Lambda supports "target typing" which infers the object type from the context in which it is used. When consumer.accept() method is called Java can infer from the context where to look for the implementation of accept() method.

Consumer functional interface andThen() method example

There is also a default method andThen() in Consumer interface.

andThen(Consumer<? super T> after)- Takes another Consumer as argument and returns a composed Consumer that performs, in sequence, first the operation of the calling Consumer followed by the after operation.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerExample {
  public static void main(String[] args) {
    // First Consumer
    Consumer<String> consumer = s -> System.out.print("Original String- " + s);
    // Adding another consumer using andThen()
    Consumer<String> consumerAfter = consumer.andThen(s ->  System.out.print(" " + s.toUpperCase() + "\n"));
    List<String> nameList = Arrays.asList("Delhi", "Bangalore", "Hyderabad", "Lucknow");
    for(String str : nameList) {
      consumerAfter.accept(str);
    }
  }
}
Output
Original String- Delhi DELHI
Original String- Bangalore BANGALORE
Original String- Hyderabad HYDERABAD
Original String- Lucknow LUCKNOW

Here first Consumer prints the passed value and second consumer prints the same value in upper case.

andThen() method is called on the instance of the first Consumer and its argument is the second consumer. When the accept() method is called on the instance of the second consumer it calls in sequence initially the first consumer and then second consumer.

Consumer functional interface in JDK

These built-in functional interfaces are used extensively with in the JDK too. One example of Consumer functional interface used quite often is when forEach() method is used to iterate a collection. Method forEach() takes Consumer as argument.

forEach(Consumer<? super E> action)- Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

The examples shown above can be written more concisely using forEach().
public class ConsumerExample {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Delhi", "Bangalore", "Hyderabad", "Lucknow");
    nameList.forEach( s -> System.out.print(s + " "));
  }
}
Output
Delhi Bangalore Hyderabad Lucknow

That's all for the topic Java Consumer Functional Interface Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like