I have a couple of Consumer<MyObject> classes I want to execute in sequence. I know I can do this with myConsumer1.andThen(myConsumer2).accept(myvalue). How can I do this if I have a List<Consumer<MyObject>> and the number of consumers is unknown?
Here is a for-loop solution that I think is not concise:
Consumer<MyObject> result;
for (Consumer<MyObject> consumer : consumers) {
if(result == null) {
result = consumer;
} else {
result.andThen(consumer);
}
}
result.apply(myvalue);
>Solution :
Loop through the list and apply each consumer to myValue.
for (Consumer<MyObject> consumer : consumerList) {
consumer.accept(myValue);
}