The Wayback Machine - https://web.archive.org/web/20241004122528/https://www.geeksforgeeks.org/java-8-consumer-interface-in-java-with-examples/
Open In App

Java 8 | Consumer Interface in Java with Examples

Last Updated : 17 Sep, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Consumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and produces a result. However these kind of functions don’t return any value.
Hence this functional interface which takes in one generic namely:- 
 

  • T: denotes the type of the input argument to the operation

The lambda expression assigned to an object of Consumer type is used to define its accept() which eventually applies the given operation on its argument. Consumers are useful when it not needed to return any value as they are expected to operate via side-effects. 
 

Functions in Consumer Interface

The Consumer interface consists of the following two functions:
 

1. accept()

This method accepts one value and performs the operation on the given argument
Syntax: 
 

void accept(T t)

Parameters: This method takes in one parameter: 
 

  • t– the input argument

Returns: This method does not return any value.
Below is the code to illustrate accept() method:
Program 1:
 

Java




// Java Program to demonstrate
// Consumer's accept() method
 
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
 
public class Main {
    public static void main(String args[])
    {
        // Consumer to display a number
        Consumer<Integer> display = a -> System.out.println(a);
 
        // Implement display using accept()
        display.accept(10);
 
        // Consumer to multiply 2 to every integer of a list
        Consumer<List<Integer> > modify = list ->
        {
            for (int i = 0; i < list.size(); i++)
                list.set(i, 2 * list.get(i));
        };
 
        // Consumer to display a list of numbers
        Consumer<List<Integer> >
            dispList = list -> list.stream().forEach(a -> System.out.print(a + " "));
 
        List<Integer> list = new ArrayList<Integer>();
        list.add(2);
        list.add(1);
        list.add(3);
 
        // Implement modify using accept()
        modify.accept(list);
 
        // Implement dispList using accept()
        dispList.accept(list);
    }
}


Output: 

10
4 2 6

 

2. andThen()

It returns a composed Consumer wherein the parameterized Consumer will be executed after the first one. If evaluation of either function throws an error, it is relayed to the caller of the composed operation.
Note: The function being passed as the argument should be of type Consumer.
Syntax: 
 

default Consumer <T> 
        andThen(Consumer<? super T> after)

Parameters: This method accepts a parameter after which is the Consumer to be applied after the current one.
Return Value: This method returns a composed Consumer that first applies the current Consumer first and then the after operation.
Exception: This method throws NullPointerException if the after operation is null.
Below is the code to illustrate andThen() method:
Program 1:
 

Java




// Java Program to demonstrate
// Consumer's andThen() method
 
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
 
public class Main {
    public static void main(String args[])
    {
 
        // Consumer to multiply 2 to every integer of a list
        Consumer<List<Integer> > modify = list ->
        {
            for (int i = 0; i < list.size(); i++)
                list.set(i, 2 * list.get(i));
        };
 
        // Consumer to display a list of integers
        Consumer<List<Integer> >
            dispList = list -> list.stream().forEach(a -> System.out.print(a + " "));
 
        List<Integer> list = new ArrayList<Integer>();
        list.add(2);
        list.add(1);
        list.add(3);
 
        // using addThen()
        modify.andThen(dispList).accept(list);
        ;
    }
}


Output: 

4 2 6

 

Program 2: To demonstrate when NullPointerException is returned.
 

Java




// Java Program to demonstrate
// Consumer's andThen() method
 
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
 
public class Main {
    public static void main(String args[])
    {
 
        // Consumer to multiply 2 to every integer of a list
        Consumer<List<Integer> > modify = list ->
        {
            for (int i = 0; i < list.size(); i++)
                list.set(i, 2 * list.get(i));
        };
 
        // Consumer to display a list of integers
        Consumer<List<Integer> >
            dispList = list -> list.stream().forEach(a -> System.out.print(a + " "));
 
        List<Integer> list = new ArrayList<Integer>();
        list.add(2);
        list.add(1);
        list.add(3);
        try {
            // using addThen()
            modify.andThen(null).accept(list);
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}


Output: 

Exception: java.lang.NullPointerException

 

Program 3: To demonstrate how an Exception in the after function is returned and handled.
 

Java




// Java Program to demonstrate
// Consumer's andThen() method
 
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
 
public class Main {
    public static void main(String args[])
    {
 
        // Consumer to multiply 2 to every integer of a list
        Consumer<List<Integer> > modify = list ->
        {
            for (int i = 0; i <= list.size(); i++)
                list.set(i, 2 * list.get(i));
        };
 
        // Consumer to display a list of integers
        Consumer<List<Integer> >
            dispList = list -> list.stream().forEach(a -> System.out.print(a + " "));
        System.out.println();
 
        List<Integer> list = new ArrayList<Integer>();
        list.add(2);
        list.add(1);
        list.add(3);
 
        // using addThen()
        try {
            dispList.andThen(modify).accept(list);
            ;
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}


Output: 

2 1 3 Exception: java.lang.IndexOutOfBoundsException: Index: 3, Size: 3

 



Previous Article
Next Article

Similar Reads

Why to Use Comparator Interface Rather than Comparable Interface in Java?
In Java, the Comparable and Comparator interfaces are used to sort collections of objects based on certain criteria. The Comparable interface is used to define the natural ordering of an object, whereas the Comparator interface is used to define custom ordering criteria for an object. Here are some reasons why you might want to use the Comparator i
8 min read
Understanding threads on Producer Consumer Problem | Java
Thread is a part of execution i.e., it is an independent path of execution in a program. A program can have more than one thread which rises the concept of multithreading. We must use java.lang.Thread class in order to use a thread to perform a specific task. In this article, let's see the implementation of the threads through a program. Whenever a
10 min read
Producer Consumer Solution using BlockingQueue in Java Thread
The Producer-Consumer problem is a synchronization issue that arises when one or more threads generate data, placing it on a buffer, and simultaneously, one or more threads consume data from the same buffer. Doing so can cause a race condition in which the threads are racing against each other to complete their task. In this scenario, nothing stops
6 min read
Apache Kafka - Create Consumer with Threads using Java
Threads are a subprocess with lightweight with the smallest unit of processes and also have separate paths of execution. These threads use shared memory but they act independently hence if there is an exception in threads that do not affect the working of other threads despite them sharing the same memory. Kafka Consumer is used to reading data fro
8 min read
Apache Kafka - Create Consumer using Java
Kafka Consumer is used to reading data from a topic and remember a topic again is identified by its name. So the consumers are smart enough and they will know which broker to read from and which partitions to read from. And in case of broker failures, the consumers know how to recover and this is again a good property of Apache Kafka. Now data for
6 min read
Apache Kafka - Consumer Seek and Assign using Java
Kafka Consumer is used to reading data from a topic and remember a topic again identified by its name. So the consumers are smart enough and will know which broker to read from and which partitions to read from. And in case of broker failures, the consumers know how to recover and this is again a good property of Apache Kafka. Now data for the cons
5 min read
Producer-Consumer solution using threads in Java
In computing, the producer-consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue. The producer's job is to generate data, put it into the buffer, and start
5 min read
Producer-Consumer solution using Semaphores in Java | Set 2
Prerequisites - Semaphore in Java, Inter Process Communication, Producer Consumer Problem using Semaphores | Set 1 In computing, the producer–consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, which share a c
5 min read
Java 8 | BiConsumer Interface in Java with Examples
The BiConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function that takes in two arguments and produces a result. However, these kinds of functions doesn't return any value. This functional interface takes in two generics, namely:- T:
5 min read
Java 8 | IntToDoubleFunction Interface in Java with Examples
The IntToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a double-valued result. The lambda expression assigned to an object of IntToDoubleFunction type is used to define
1 min read
Java 8 | DoubleToLongFunction Interface in Java with Examples
The DoubleToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an long-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to defi
1 min read
Java 8 | IntToLongFunction Interface in Java with Examples
The IntToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a long-valued result. The lambda expression assigned to an object of IntToLongFunction type is used to define its ap
1 min read
Java.util.function.BiPredicate interface in Java with Examples
The BiPredicate<T, V> interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on two objects and returns a predicate value based on that condition. It is a functional interface and thus can be used in lambda expression also. public interface BiPredicate<T, V> Methods: test(): This functio
2 min read
Java.util.function.DoublePredicate interface in Java with Examples
The DoublePredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a Double object and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface DoublePredicate Methods test(): This function evaluates a co
2 min read
Java.util.function.LongPredicate interface in Java with Examples
The LongPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a long value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface LongPredicate Methods test(): This function evaluates a condition
2 min read
Java.util.function.IntPredicate interface in Java with Examples
The IntPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on an integer value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface IntPredicate Methods: test(): This function evaluates a condit
2 min read
How Kafka Consumer and Deserializers Work in Apache Kafka?
Kafka Consumers is used to reading data from a topic and remember a topic again is identified by its name. So the consumers are smart enough and they will know which broker to read from and which partitions to read from. And in case of broker failures, the consumers know how to recover and this is again a good property of Apache Kafka. Now data for
2 min read
Spring Boot Kafka Consumer Example
Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can "just run". So some of the main
3 min read
How to Create Apache Kafka Consumer with Conduktor?
Kafka Consumers is used to reading data from a topic and remember a topic again is identified by its name. So the consumers are smart enough and they will know which broker to read from and which partitions to read from. And in case of broker failures, the consumers know how to recover and this is again a good property of Apache Kafka. Now data for
3 min read
Apache Kafka Consumer
Kafka Consumers is used to reading data from a topic and remember a topic again is identified by its name. So the consumers are smart enough and they will know which broker to read from and which partitions to read from. And in case of broker failures, the consumers know how to recover and this is again a good property of Apache Kafka. Now data for
5 min read
Apache Kafka - Create Consumers in a Consumer Group using CLI
In Apache Kafka, a consumer group is a set of consumers that work together to consume a topic. A set of partitions is given to each group member consumer to choose from. When a consumer in the group finishes consuming a message from its assigned partition, it sends a message to the Kafka broker to commit the offset (the position of the consumer in
4 min read
ToLongFunction Interface in Java with Examples
The ToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an argument of type T and produces a long-valued result. This functional interface takes in only one generic, namely:- T: denotes the type of the input
1 min read
LongToIntFunction Interface in Java with Examples
The LongToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a long-valued argument and gives an int-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to define its
1 min read
ToIntFunction Interface in Java with Examples
The ToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an argument of type T and produces an int-valued result. This functional interface takes in only one generic, namely:- T: denotes the type of the input a
1 min read
ToDoubleFunction Interface in Java with Examples
The ToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an argument of type T and produces a double-valued result. This functional interface takes in only one generic, namely:- T: denotes the type of the in
1 min read
IntFunction Interface in Java with Examples
The IntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and produces a result of type R. This functional interface takes in only one generic, namely:- R: denotes the type of the output of
1 min read
LongFunction Interface in Java with Examples
The LongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a long-valued argument and produces a result of type R. This functional interface takes in only one generic, namely:- R: denotes the type of the output of
1 min read
ToDoubleBiFunction Interface in Java with Examples
The ToDoubleBiFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in two arguments of type T and U and produces a double-valued result. This functional interface takes in two generics, namely:- T: denotes the type of
2 min read
ToIntBiFunction Interface in Java with Examples
The ToIntBiFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in two arguments of type T and U and produces an int-valued result. This functional interface takes in two generics, namely:- T: denotes the type of the f
2 min read
ToLongBiFunction Interface in Java with Examples
The ToLongBiFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in two arguments of type T and U and produces an long-valued result. This functional interface takes in two generics, namely:- T: denotes the type of the
2 min read
Practice Tags :