Java Consumer Interface

Introduction

In this blog we will learn how to use Consumer functional interface in java.util.Function.

Consumer as the name suggest will consume whatever is sent across and will not return anything.

Consumer<T> accepts the argument and perform operations on it but do not return anything.

Consumer<T> functional method is void accept(T t).

In the below example we can see Consumer interface accepts a integer and prints it , without returning anything.

Consumer example 1:

1
2
3
4
5
6
7
Consumer<Integer> test = new Consumer<Integer>() {
@Override
public void accept(Integer x) {
                System.out.println(x);
            }
        };
test.accept(10);
1
2
Output:
10

We can write same code using lambda expresssion.

1
2
Consumer<Integer> test = x-> System.out.println(x);
test.accept(10);

Consumer example 2

In the below example we can accept list as an argument in Consumer interface.

1
2
3
4
Consumer<List<Integer>> numsConsumer = list
-> list.stream().forEach(System.out::println);

numsConsumer.accept(nums);
1
2
3
4
5
6
7
Output:

10
20
30
40
50

Composed Consumer

We can chain multiple consumer of the same type together to perform operations in sequence.

We can perform this using andThen() method which returns a composed Consumer that performs, in sequence, this operation followed by the after operation

1
2
3
4
default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t) -> { accept(t); after.accept(t); };
}

In the below example we define 2 consumers.

First one just prints the number consumed

Second consumes and increments the number.

We create composed consumer and pass a number.

It performs operation in sequence and prints 100 and 101.

1
2
3
4
5
6
Consumer<Integer> first = x-> System.out.println(x);
Consumer<Integer> second = x-> System.out.println(x+1);

Consumer<Integer> composedConsumer = first.andThen(second);

composedConsumer.accept(100);

BiConsumer

BiConsumer<T,U> is similar to Consumer, but here it accepts 2 arguments. For some use cases we may want to accept 2 argument and perform operations on them.

Functional method signature is as follows

1
void accept(T t, U u);

In the below example , we accept 2 Integer arguments and print the sum of those numbers.

1
2
BiConsumer<Integer,Integer> sum = (x,y) -> System.out.println(x+y);
sum.accept(10,20); // 30

Conclusion

I hope this tutorial has helped you to get started with Consumer Interface in Java.

Learn more functional interfaces

  1. Function interface
  2. Predicate interface
  3. BiPredicate interface
  4. BiFunction interface
  5. Supplier interface