Java : DoubleConsumer with Examples

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


Summary

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

Class diagram

final var stream = DoubleStream.of(0.25, 0.5, 1.0, 2.0);

final var action = new DoubleConsumer() {
    @Override
    public void accept(double value) {
        final var hex = Double.toHexString(value);
        System.out.println(hex);
    }
};

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

// Result
// ↓
//-- forEach --
//0x1.0p-2
//0x1.0p-1
//0x1.0p0
//0x1.0p1
// An example with a lambda expression.
final var stream = DoubleStream.of(0.25, 0.5, 1.0, 2.0);

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

// Result
// ↓
//-- forEach --
//0x1.0p-2
//0x1.0p-1
//0x1.0p0
//0x1.0p1

Methods

void accept (double value)

Performs this operation on the given argument.

final var stream = DoubleStream.of(0.25, 0.5, 1.0, 2.0);

final var action = new DoubleConsumer() {
    @Override
    public void accept(double value) {
        final var hex = Double.toHexString(value);
        System.out.println(hex);
    }
};

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

// Result
// ↓
//-- forEach --
//0x1.0p-2
//0x1.0p-1
//0x1.0p0
//0x1.0p1
// An example with a lambda expression.
final var stream = DoubleStream.of(0.25, 0.5, 1.0, 2.0);

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

// Result
// ↓
//-- forEach --
//0x1.0p-2
//0x1.0p-1
//0x1.0p0
//0x1.0p1

default DoubleConsumer andThen (DoubleConsumer after)

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

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

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

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

// Result
// ↓
//before : 1.23
//after  : 1.23

Related posts

To top of page