Java 8 Consumer Interface
7 years ago Lalit Bhagtani 0
In this tutorial, we will learn about 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 :-
- Stream<T> peek ( Consumer<? super T> action )
- void forEach ( Consumer<? super T> action )
- 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 :-
- IntConsumer interface ( JavaDocs ) :- It represents an operation that accepts one integer as an argument and returns no value.
- DoubleConsumer interface ( JavaDocs ) :- It represents an operation that accepts one double as an argument and returns no value.
- 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.