Java 8 Consumer Interface

9 months ago codedestine 0

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

Java 8 consumer interface

Consumer Interface :-

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

Abstract method :-  

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

Default method :-  

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

Reference :-  Consumer Interface JavaDocs 

 Stream API have few methods where Java 8 Consumer interface are used as an argument, they are as follows :-

  1. Stream<T>  peek ( Consumer<? super T> action )
  2. void  forEach ( Consumer<? super T> action )
  3. void  forEachOrdered ( Consumer<? super T> action )

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

  1. IntConsumer interface ( JavaDocs ) :- It represents an operation that accepts one integer as an argument and returns no value.
  2. DoubleConsumer interface ( JavaDocs ) :- It represents an operation that accepts one double as an argument and returns no value.
  3. LongConsumer interface ( JavaDocs ) :- It represents an operation that accepts 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 java 8 consumer interface.

  public static void main(String[] args){
 
    Consumer<String> consumer1 = ( x ) -> { System.out.println(x + " 1st"); };
 
    // Example of accept 
    consumer1.accept("BiConsumer");
 
    Consumer<String> consumer2 = ( x ) -> { System.out.println(x + " 2nd"); };
 
    // Example of andThen
    consumer1.andThen(consumer2).accept("BiConsumer"); 
  }

Result :- 

BiConsumer 1st
BiConsumer 1st
BiConsumer 2nd

Example – 2 :- 

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

  public static void main(String[] args){ 
 
    List<String> names = new ArrayList<String>();
    names.add("Robert");
    names.add("Martin");
    names.add("Jack");
    names.add("Anil");
 
    names.forEach( n -> System.out.println("Names : " + n));
  }

Result :- 

Names : Robert
Names : Martin
Names : Jack
Names : Anil

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