Java : IntConsumer with Examples

IntConsumer (Java SE 21 & JDK 21) with Examples.
You will find code examples on most IntConsumer methods.


Summary

Represents an operation that accepts a single int-valued argument and returns no result. This is the primitive type specialization of Consumer for int. Unlike most other functional interfaces, IntConsumer is expected to operate via side-effects.

Class diagram

final var stream = IntStream.of(1, 10, 16, 255);

final var action = new IntConsumer() {
    @Override
    public void accept(int value) {
        final var hex = "0x" + Integer.toHexString(value);
        System.out.println(hex);
    }
};

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

// Result
// ↓
//-- forEach --
//0x1
//0xa
//0x10
//0xff
// An example with a lambda expression.
final var stream = IntStream.of(1, 10, 16, 255);

System.out.println("-- forEach --");
stream.forEach(value -> {
    final var hex = "0x" + Integer.toHexString(value);
    System.out.println(hex);
});

// Result
// ↓
//-- forEach --
//0x1
//0xa
//0x10
//0xff

Methods

void accept (int value)

Performs this operation on the given argument.

final var stream = IntStream.of(1, 10, 16, 255);

final var action = new IntConsumer() {
    @Override
    public void accept(int value) {
        final var hex = "0x" + Integer.toHexString(value);
        System.out.println(hex);
    }
};

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

// Result
// ↓
//-- forEach --
//0x1
//0xa
//0x10
//0xff
// An example with a lambda expression.
final var stream = IntStream.of(1, 10, 16, 255);

System.out.println("-- forEach --");
stream.forEach(value -> {
    final var hex = "0x" + Integer.toHexString(value);
    System.out.println(hex);
});

// Result
// ↓
//-- forEach --
//0x1
//0xa
//0x10
//0xff

default IntConsumer andThen (IntConsumer after)

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

final var before = new IntConsumer() {
    @Override
    public void accept(int value) {
        System.out.println("before : " + value);
    }
};

final var after = new IntConsumer() {
    @Override
    public void accept(int value) {
        System.out.println("after  : " + value);
    }
};

final var consumer = before.andThen(after);
consumer.accept(123);

// Result
// ↓
//before : 123
//after  : 123

Related posts

To top of page