Java8 Primitive Consumer Interface examples| Functional Interface tutorials

Learn about primitive Consumers in java8 with examples.

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.

java8 IntConsumer class

IntConsumer is an interface defined in java.util.function package. It has only a 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.

import java.util.Arrays;
import java.util.function.IntConsumer;

public class Test {
    public static void main(String[] args)  throws Exception{
        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:

51
110
8 7 3 1

java8 LongConsumer class

LongConsumer interface is defined in java.util.function package in java8.

It takes a 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.

Following is a code for accept and andthen method Example

import java.util.function.LongConsumer;

public class Test {
    public static void main(String[] args)  throws Exception{
        LongConsumer longConsumer1 = (value ) -> { System.out.println(value); };
        longConsumer1.accept(5);
        LongConsumer longConsumer2 = ( value) -> { System.out.println(value); };
        longConsumer1.andThen(longConsumer2).accept(4);
    }
}

Output:

5
4
4

Java8 DoubleConsumer class

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

import java.util.function.DoubleConsumer;

public class Test {
    public static void main(String[] args)  throws Exception{
        DoubleConsumer multiplyDoubleConsumer= (value) -> System.out.println(value*value);
        multiplyDoubleConsumer.accept(.5);
    }
}

Output:

0.25

Conclusion

In this tutorial, Learn about primitive consumer interface types - IntConsumer, DoubleConsumer, LongConsumer functional interfaces with examples