Java : LongConsumer with Examples

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


Summary

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

Class diagram

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

final var action = new LongConsumer() {
    @Override
    public void accept(long value) {
        final var hex = "0x" + Long.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 = LongStream.of(1, 10, 16, 255);

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

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

Methods

void accept (long value)

Performs this operation on the given argument.

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

final var action = new LongConsumer() {
    @Override
    public void accept(long value) {
        final var hex = "0x" + Long.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 = LongStream.of(1, 10, 16, 255);

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

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

default LongConsumer andThen (LongConsumer after)

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

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

final var after = new LongConsumer() {
    @Override
    public void accept(long 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