Java : Consumer with Examples

Consumer (Java SE 19 & JDK 19) API Examples.
You will find code examples on most Consumer methods.


Summary

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

Class diagram

final var stream = Stream.of("a", "b", "c");

final var action = new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println(s.toUpperCase().repeat(3));
    }
};

// AAA
// BBB
// CCC
stream.forEach(action);
// An example with a lambda expression.
final var stream = Stream.of("a", "b", "c");

// AAA
// BBB
// CCC
stream.forEach(s -> System.out.println(s.toUpperCase().repeat(3)));

Methods

void accept (T t)

Performs this operation on the given argument.

final var consumer = new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println(s.toUpperCase());
    }
};

consumer.accept("abcd"); // ABCD
final var consumer = new Consumer<LocalDate>() {
    @Override
    public void accept(LocalDate date) {
        System.out.println(date);
    }
};

consumer.accept(LocalDate.of(1999, 1, 1)); // 1999-01-01
// An example with a lambda expression.
final var list = List.of("AAA", "BBB", "CCC");
System.out.println(list); // [AAA, BBB, CCC]

// aaa
// bbb
// ccc
list.forEach(s -> System.out.println(s.toLowerCase()));

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

Returns a composed Consumer that performs, in sequence, this operation followed by the after operation.

final var consumer1 = new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println(s);
    }
};

final var after = new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println(s.toUpperCase());
    }
};

final var consumer2 = consumer1.andThen(after);

// abcd
// ABCD
consumer2.accept("abcd");
final var consumer1 = new Consumer<String>() {
    @Override
    public void accept(String s) {
        if (s == null) {
            throw new IllegalArgumentException("s is null");
        }
        System.out.println("accept : " + s);
    }
};

final var after = new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println("after : " + s);
    }
};

final var consumer2 = consumer1.andThen(after);
consumer2.accept(null);

// Result
// ↓
// java.lang.IllegalArgumentException: s is null

Related posts

To top of page