maxpovver maxpovver - 1 year ago 74
Java Question

Apply Consumer many times at once using standard library

Are there any ways to use consumer in chain without writing code or adding additional libraries?
Now it's like:

Consumer s = str -> System.out.println(str);

Is there a way to turn it into something like

Consumer s = str -> System.out.println("str");


Answer Source

As others have mentioned Consumer returns void so you can't chain them. But everything comes down to how complex is the thing you are trying to achieve. For instance your particular example could have been written in such way:

Stream.of("abc", "fgh", "xyz").forEach(System.out::println);

Strings can be replace with any object and the Consumer can be of any complexity. However if you don't need to execute consumer on every value in one chain then this approach won't fit you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download