Java 8 BiConsumer Interface

11 months ago codedestine 0

In this tutorial, we will learn about Java 8 BiConsumer interface.

Java 8 BiConsumer Interface

BiConsumer Interface :-

BiConsumer ( java.util.function.BiConsumer ) is a functional interface that has one abstract method and one default method declared in it.

Abstract method :-  

void  accept ( T t , U u ) :- The abstract method accept ( T t , U u ) is a functional method. It accepts two parameters as an argument and return no value, it performs the operation defined by the BiConsumer interface ( usually a lambda expression passed as an argument ). 

Default method :-

default  BiConsumer< T , U >  andThen ( BiConsumer<? super T, ? super U> after ) :- It returns a biconsumer that performs two operation in sequence, first the operation of the biconsumer on which method is called followed by the operation of the biconsumer passed as an argument.

Reference :-  BiConsumer Interface JavaDocs 

Java 8 also provides us three specialised form of BiConsumer interface, which can be used in case of int, long and double. They are as follows :-

  1. ObjIntConsumer interface ( JavaDocs ) :- It represents an operation that accepts two parameters ( one Object and one integer ) as an argument and returns no value.
  2. ObjDoubleConsumer interface ( JavaDocs ) :- It represents an operation that accepts two parameters ( one Object and one double ) as an argument and returns no value.
  3. ObjLongConsumer interface ( JavaDocs ) :- It represents an operation that accepts two parameters ( one Object and one long ) as an argument and returns no value.

Example – 1 :- 

This example will show you, how to create and call different methods of a biconsumer interface.

  public static void main(String[] args){
 
    BiConsumer<String, String> biConsumer = ( x , y ) -> { System.out.println(x + " " +y);};
 
    // Example of accept 
    biConsumer.accept("BiConsumer","Interface");
 
    BiConsumer<Integer, Integer> biConMultiply = ( x , y ) -> { System.out.println(x * y);};
 
    BiConsumer<Integer, Integer> biConDivide = ( x , y ) -> { System.out.println(x / y);};
 
    // Example of andThen
    biConMultiply.andThen(biConDivide).accept(10,2); 
 }

Result :- 

BiConsumer Interface
20
5

Example – 2 :- 

In this example, we will print all the key and values of a map by using its forEach() method. This method takes one BiConsumer as an argument.

  public static void main(String[] args){ 
 
    Map<Integer,String> map = new HashMap<Integer,String>();
    map.put(1,"Robert");
    map.put(2,"Martin");
    map.put(3,"Jack");
 
    map.forEach((k,v) -> System.out.println("Key : "+ k + " , Value : "+ v ));
 }

Result :- 

Key : 1 , Value : Robert
Key : 2 , Value : Martin
Key : 3 , Value : Jack

That’s all for Java 8 BiConsumer Interface. If you liked it, please share your thoughts in comments section and share it with others too.