Java : BiConsumer with Examples

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


Summary

Represents an operation that accepts two input arguments and returns no result. This is the two-arity specialization of Consumer. Unlike most other functional interfaces, BiConsumer is expected to operate via side-effects.

Class diagram

final var map = Map.of("aaa", 10, "bbb", 20, "ccc", 30);
System.out.println(map); // {ccc=30, aaa=10, bbb=20}

final var action = new BiConsumer<String, Integer>() {
    @Override
    public void accept(String key, Integer value) {
        System.out.printf("key = %s : value = %d%n", key, value);
    }
};

map.forEach(action);

// Result
// ↓
//key = ccc : value = 30
//key = aaa : value = 10
//key = bbb : value = 20

// An example with a lambda expression.
map.forEach((key, value) -> System.out.printf("key = %s : value = %d%n", key, value));

// Result
// ↓
//key = ccc : value = 30
//key = aaa : value = 10
//key = bbb : value = 20

Methods

void accept (T t, U u)

Performs this operation on the given arguments.

final var biConsumer = new BiConsumer<String, Integer>() {
    @Override
    public void accept(String t, Integer u) {
        System.out.printf("t = %s : u = %d%n", t, u);
    }
};

biConsumer.accept("abcd", 123);

// Result
// ↓
//t = abcd : u = 123

default BiConsumer<T,U> andThen (BiConsumer<? super T,? super U> after)

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

final var biConsumer1 = new BiConsumer<StringBuilder, Integer>() {
    @Override
    public void accept(StringBuilder sb, Integer value) {
        System.out.println("-- before --");
        sb.append("value = %d%n".formatted(value));
        System.out.print(sb);
    }
};

final var biConsumer2 = biConsumer1.andThen((sb, value) -> {
    System.out.println("-- after --");
    sb.append("value = %d%n".formatted(value * 10));
    System.out.print(sb);
});


biConsumer2.accept(new StringBuilder(), 123);

// Result
// ↓
//-- before --
//value = 123
//-- after --
//value = 123
//value = 1230

Related posts

To top of page