×

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 Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.