Java : LongConsumer with Examples
LongConsumer (Java SE 21 & JDK 21) with Examples.
You will find code examples on most LongConsumer methods.
Summary
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)
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)
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