Consumer
is a functional interface that accepts an argument and returns no result.
The interface contains two methods:
accept()
andThen()
The Consumer
interface is defined in the java.util.function
package.
Use the following statement to import the Consumer
interface.
import java.util.function.Consumer;
accept()
This method accepts a single input and performs the given operation on the input without returning any result.
void accept(T t)
T t
: The input argument.The method doesn’t return any result.
import java.util.function.*;public class Main{public static void main(String[] args) {// Implementation of Consumer interface that consumes and prints the passed valueConsumer<String> consumer = (t) -> System.out.println("The passed parameter is - " + t);String parameter = "hello-educative";// calling the accept method to execute the print operationconsumer.accept(parameter);}}
In the code above, we created an implementation of the Consumer
interface that prints the passed argument to the console.
andThen()
This method is used to chain multiple Consumer
interface implementations one after another. The method returns a composed consumer of different implementations defined in the order. If the evaluation of any Consumer
implementation along the chain throws an exception, it is relayed to the caller of the composed function.
default Consumer<T> andThen(Consumer<? super T> after)
Consumer<? super T> after
: The next implementation of the consumer to evaluate.The method returns a composed Consumer
that performs in sequence the defined operation, followed by the after operation.
import java.util.Arrays;import java.util.List;import java.util.function.Consumer;public class Main{static class Student{public int age;public String name;public Student(int age, String name) {this.age = age;this.name = name;}@Overridepublic String toString() {return "Student{" +"age=" + age +", name='" + name + '\'' +'}';}}public static void main(String[] args) {Consumer<Student> consumer1 = s1 -> s1.age += 1;Consumer<Student> consumer2 = System.out::println;List<Student> studentList = Arrays.asList(new Student(18, "andy"), new Student(19, "jack"), new Student(20, "Dan"));System.out.println("Before chaining:");studentList.forEach(consumer2);System.out.println("----");System.out.println("After chaining:");studentList.forEach(consumer1.andThen(consumer2));}}
Main
class.Student
class with name
and age
as the attributes of that class. We define the constructor
and the toString()
method of the class.Main
class.consumer1
, which accepts a Student
object and increases the age of the Student
by one.consumer2
, which accepts a Student
object and prints it to the console.Student
objects with different values for name
and age
.Student
objects defined in line 28 using the forEach()
that accepts a consumer implementation.consumer2
to consumer1
using the andThen()
method on consumer1
object.