Java 8 : java.util.function.Consumer Functional Interface

This article describes Java 8 Consumer Functional Interface with examples.

What is a Consumer ?

Consumer is a functional interface added in Java 8 that has a single abstract method accept().

A Consumer is used when you want to perform an operation that takes a parameter but doesn’t return anything.

Here is how the Consumer Functional Interface looks like :


@FunctionalInterface public class Consumer<T> {

    void accept(T t); // Performs this operation on the given argument.    
}

 

Consumer Example 1

In this example, we create a consumer “print” that accepts any String argument and prints it.

Consumer<String> print = x -> System.out.println(x);
print.accept("abc");

Output:

abc
 

Consumer Example 2 :

In this example, we create a consumer print using method reference(::).

Consumer<String> print = System.out::println;
print.accept("abc");

Output:

abc
 

Consumer Example 3 :

This example prints an array of String elements using a Consumer.

Consumer<String> print = name -> System.out.println(name);
for (String name : Arrays.asList("John", "Dave", "Chris")) {
  print.accept(name);
}

Output:

John
Dave
Chris
 

Difference between Consumer and Supplier

  • Consumer: Takes input, processes it.. but doesn’t return anything.
  • Supplier: Returns output without taking any input.

 

Read more about Supplier functional interface.

 

Primitive Consumers

IntConsumer

Accepts a single int-valued argument and returns no result.

    IntConsumer printInt = i -> System.out.println(Integer.toString(i));
    printInt.accept(10);

Output:

10
 
DoubleConsumer

Accepts a single double-valued argument and returns no result.
 
LongConsumer

Accepts a single long-valued argument and returns no result.

 

© 2017 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags