I am new in Java 8 and are messing around a little bit.
Now I've tried the andThen method of the functional interface Consumer in Java 8:
public static void main(String[] args) {
List<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
ints.add(i);
}
Consumer<Integer> cons1 = in -> System.out.println("--> " + in);
ints.forEach(cons1.andThen(in -> System.out.println("-+---> " + in)));
}
It works fine! The output is:
--> 0
-+---> 0
--> 1
-+---> 1
--> 2
-+---> 2
--> 3
-+---> 3
--> 4
-+---> 4
Now, I am asking myself if I can concat the both consumers (with the andThen method) without creating an own object for the first consumer cons1?
Yes, but it'll be messier than the straightforward ways of doing it.
You could write
ints.forEach(
((Consumer<Integer>) in -> System.out.println("--> " + in))
.andThen(in -> System.out.println("-+---> " + in)));
but it'd be much better to just write
ints.forEach(in -> {
System.out.println("--> " + in);
System.out.println("-+---> " + in);
});
You could use a cast like in Louis Wasserman's answer.
The "problem" is that a lambda expression can only appear in three different context: assignment context, casting context and invocation context. In your example, you are using an assignment context to create that lambda expression.
It would be nice to be able to write (a -> b).andThen(c -> d) but unfortunately, a lambda expression can't appear in that context... What you can do, is create an invocation context by factoring the consumers into specific methods. You can even make them generic by adding a generic type.
public static void main(String[] args) {
List<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
ints.add(i);
}
ints.forEach(printFirst().andThen(printSecond()));
}
private static <T> Consumer<? super T> printFirst() {
return in -> System.out.println("--> " + in);
}
private static <T> Consumer<? super T> printSecond() {
return in -> System.out.println("-+---> " + in);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With