The chain with andThen really a way to go, but we need some sort of syntactic sugar to make it beautiful:
public class Consumers { public static <T> Consumer<T> of(Consumer<T> base) { return base; } }
This allows us to do:
Arrays.asList("a", "b", "c") .stream() .forEach(Consumers.of(s -> System.out.println(s + "1")) .andThen(s -> System.out.println(s + "2")) .andThen(s -> System.out.println(s + "3")));
Or (in short):
Arrays.asList("a", "b", "c") .forEach(Consumers.of(s -> System.out.println(s + "1")) .andThen(s -> System.out.println(s + "2")) .andThen(s -> System.out.println(s + "3")));
(since forEach available directly in the collection)
marthursson
source share