×

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t return any value. The Consumer Interface is present in the java. util package. The Consumer interface takes only one generic argument “T”, it denotes the type of input.

An object of the Consumer type is provided a lambda expression, which is used to construct the accept() method, which finally applies the specified operation to its argument. Since consumers are expected to function through side effects, they are helpful when no value needs to be returned.

Functions used in Consumer Interface:

  • accept():
    The accept() method accept an argument and executes the operation on specified argument.
    Syntax:
void accept(T obj)

The accept() method doesn’t return any value.

  • andThen():
    The parameterized Consumer will be invoked afterwards the first one in the composed consumer that andThen() method returns. The caller of the composed operation is informed if any errors that are thrown during the evaluation of either function.

Syntax:

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

Example Program:

// 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 Consumer {
    public static void main(String args[])
    {
        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:

2 4 6

Example 2:

// 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 Consumer {
    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 out of bounds for length 3

Summary:

The Consumer Interface is used to implement the functional programming in Java. In the Consumer Interface, it only takes a single argument and return the result. The Consumer Interface is preferred to use only when the function doesn’t return any value.


Related Topics

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.