Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Consumer andThen method works internally in java functional interfaces

Tags:

java

java-8

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");
  }
}
like image 383
sidhartha pani Avatar asked May 29 '17 07:05

sidhartha pani


1 Answers

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.

like image 106
Eugene Avatar answered Sep 30 '22 18:09

Eugene