Java8 Primitive Consumer Interface examples| Functional Interface tutorials


java.util.function.consumer Interface 

Java 8 introduced different consumer interfaces in java.util.function package.

IntConsumer

LongConsumer

DoubleConsumer

Consumer is an operation that accepts numeric values and outputs no result.

In my previous post, documented consumer tutorials.

IntConsumer

It has an only single abstract method - accept() which takes an input value and returns nothing

And also default method - andThen(IntConsumer after) - Returns aggregation consumer of called consumer with after consumer result

IntConsumer consumer = value -> System.out.println(value);  
consumer.accept(51);  
consumer.accept(110);  
int[] numbers = {8,7,3,1};  
IntConsumer intConsumerFunction = value -> System.out.print(value+" ");  
Arrays.stream(numbers).forEach(intConsumerFunction);  

Output is

51  
110  
8 7 3 1 

LongConsumer

LongConsumer interface is defined in java.util.function package in java8 language. it takes long input value and output no result.

It has only one abstract method -accept()

Default method - andThen(LongConsumer after) - returns aggregate compose consumer of called consumer with the operation of after result consumer

accept and andthen Example

LongConsumer longConsumer1 = ( value ) -> { System.out.println(value); };   
longConsumer1.accept(5);  
LongConsumer longConsumer2 = ( value) -> { System.out.println(value); };   
longConsumer1.andThen(longConsumer2).accept(4);  

Output is

5  
4  
4

DoubleConsumer

DoubleConsumer is an inbuilt interface defined in java.util.function package in java8. This has only accept abstract method, takes a double value and produces no output
And also andThen default method

DoubleConsumer multiplyDoubleConsumer= (value) -> System.out.println(value*value);  
multiplyDoubleConsumer.accept(.5);  

Output is

0.25
Similar Posts