Java : Consumer with Examples

Consumer (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Consumer<T> 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));
    }
};

System.out.println("-- forEach --");
stream.forEach(action);

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

System.out.println("-- forEach --");
stream.forEach(s -> {
    System.out.println(s.toUpperCase().repeat(3));
});

// Result
// ↓
//-- forEach --
//AAA
//BBB
//CCC

Methods

void accept (T t)

Performs this operation on the given argument.

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));
    }
};

System.out.println("-- forEach --");
stream.forEach(action);

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

System.out.println("-- forEach --");
stream.forEach(s -> {
    System.out.println(s.toUpperCase().repeat(3));
});

// Result
// ↓
//-- forEach --
//AAA
//BBB
//CCC

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);

System.out.println("-- accept --");
consumer2.accept("abcd");

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

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

final var consumer2 = consumer1.andThen(after);

try {
    System.out.println("-- accept null --");
    consumer2.accept(null);
} catch (IllegalArgumentException e) {
    System.out.println("IllegalArgumentException! : " + e.getMessage());
}

// Result
// ↓
//-- accept null --
//  consumer1 accept!
//IllegalArgumentException! : s is null

Related posts

To top of page