Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Execute Consumers in a row

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Loop through the list and apply each consumer to myValue.

for (Consumer<MyObject> consumer : consumerList) {
        consumer.accept(myValue);
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading