The shortest representation of special lambda expressions in Java 8
•
Java
I'm new to Java 8 and I'm messing up a little
Now I have tried the andthen method of the function 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! The output is:
--> 0 -+---> 0 --> 1 -+---> 1 --> 2 -+---> 2 --> 3 -+---> 3 --> 4 -+---> 4
Now, I ask myself if I can connect two consumers (using the andthen method) without creating my own object for the first consumer cons1?
Solution
Yes, but it will be more confusing than a straightforward approach
You can write
ints.forEach( ((Consumer<Integer>) in -> System.out.println("--> " + in)) .andThen(in -> System.out.println("-+---> " + in)));
But it's much better to write
ints.forEach(in -> { System.out.println("--> " + in); System.out.println("-+---> " + in); });
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码