Java : Consumer with Examples
Consumer (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Consumer<T> methods.
Summary
final var stream = Stream.of("a", "b", "c");
final var action = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s.toUpperCase().repeat(3));
}
};
System.out.println("-- forEach --");
stream.forEach(action);
// Result
// ↓
//-- forEach --
//AAA
//BBB
//CCC
// An example with a lambda expression.
final var stream = Stream.of("a", "b", "c");
System.out.println("-- forEach --");
stream.forEach(s -> {
System.out.println(s.toUpperCase().repeat(3));
});
// Result
// ↓
//-- forEach --
//AAA
//BBB
//CCC
Methods
void accept (T t)
final var stream = Stream.of("a", "b", "c");
final var action = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s.toUpperCase().repeat(3));
}
};
System.out.println("-- forEach --");
stream.forEach(action);
// Result
// ↓
//-- forEach --
//AAA
//BBB
//CCC
// An example with a lambda expression.
final var stream = Stream.of("a", "b", "c");
System.out.println("-- forEach --");
stream.forEach(s -> {
System.out.println(s.toUpperCase().repeat(3));
});
// Result
// ↓
//-- forEach --
//AAA
//BBB
//CCC
default Consumer<T> andThen (Consumer<? super T> after)
final var consumer1 = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
final var after = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s.toUpperCase());
}
};
final var consumer2 = consumer1.andThen(after);
System.out.println("-- accept --");
consumer2.accept("abcd");
// Result
// ↓
//-- accept --
//abcd
//ABCD
final var consumer1 = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(" consumer1 accept!");
if (s == null) {
throw new IllegalArgumentException("s is null");
}
}
};
final var after = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(" after accept!");
}
};
final var consumer2 = consumer1.andThen(after);
try {
System.out.println("-- accept null --");
consumer2.accept(null);
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException! : " + e.getMessage());
}
// Result
// ↓
//-- accept null --
// consumer1 accept!
//IllegalArgumentException! : s is null