can someone let me know how the below program works internally:
public class Main {
public static void main(String[] args) {
Consumer<String> c = (x) -> System.out.println(x.toLowerCase());
c.andThen(c).andThen(c).accept("Java2s.com");
}
}
Did you look at the code of andThen
?
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
It's creating a new Consumer for each call to andThen
, finally at the end invoking the accept
method (which is the only abstract one).
How about a different approach:
Consumer<String> first = x -> System.out.println(x.toLowerCase());
Consumer<String> second = y -> System.out.println("aaa " + y);
Consumer<String> result = first.andThen(second);
Running this code is not going to produce anything, since you have not invoked accept
anywhere just yet.
On the other hand, you can see what happens when calling accept
on each other:
Consumer<String> result = first.andThen(second);
first.accept("Java"); // java
second.accept("Java"); // aaa Java
System.out.println("---------");
result.accept("Java"); // java, aaa Java
andThen
returns a composition of this Consumer with the next one.
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