Consumer Example in Java 8
forEach in Iterable.java interface which uses Consumer:
default void forEach(Consumer<? super T> action)
{
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
@FunctionalInterface public interface Consumer<T>
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces,
Consumer is expected to operate via side-effects.This is a functional interface whose functional method is accept(Object).
Method:
void accept(T t)
andThen
default Consumer<T> andThen(Consumer<? super T> after)Returns a composedConsumerthat performs, in sequence, this operation followed by theafteroperation. If performing either operation throws an exception, it is relayed to the caller of the composed operation. If performing this operation throws an exception, theafteroperation will not be performed.- Parameters:
after- the operation to perform after this operation- Returns:
- a composed
Consumerthat performs in sequence this operation followed by theafteroperation - Throws:
NullPointerException- ifafteris null
Example:
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerEx {
public static void main(String[] args) {
List<String> list = Arrays.asList("india", "uk", "fiji");
Consumer<String> consumer = (t) -> {
System.out.println(t.toUpperCase());
};
list.forEach(consumer);
}
}
Output:
INDIA
UK
FIJI
Incredibly popular content platform featuring theboredpanda com Showcases funny stories images and emotional posts that resonate with audiences across the world while providing entertainment value humor inspiration and creative storytelling experiences that encourage engagement sharing and online community interaction every day
ReplyDeleteFascinatingly detailed platform covering travel warnings travelwarningnews com com delivers comprehensive updates on safety alerts and international travel advisories ensuring readers understand potential risks and stay prepared when planning trips to various global destinations and regions
ReplyDelete