I been looking at java FunctionalInterface java.util.function.Consumer which have the source code
package java.util.function;
import java.util.Objects;
public interface Consumer<T> {
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
so if I call consumer1.andThen(consumer2)... andThen(consumerN).accept(); it seem to me that this is effectively creating N + (N - 1) of Consumer Objects. Please let me know if I am using it wrong or am I not supposed to use it that way.
Here is my test code to test the issue. Am I missing something??
public class Test1 {
public static int c = 0;
public static int acceptC = 0;
public Test1(){
++c;
System.out.println("new Object Created = "+c);
}
public void accept(int i){
acceptC++;
System.out.println("accept call "+ acceptC);
}
public Test1 andThen(Test1 after) {
return new Test1(){
@Override
public void accept(int i) {
acceptC++;
System.out.println("accept call in temp = " +acceptC) ;
Test1.this.accept(++i); after.accept(++i);
}
};
}
public static void main(String args[]){
Test1 t1 = new Test1();
Test1 t2 = new Test1();
Test1 t3 = new Test1();
Test1 t4 = new Test1();
Test1 t5 = new Test1();
t1.andThen(t2).andThen(t3).andThen(t4).andThen(t5).accept(0);
System.out.println("RESULT total Test Object created ="+Test1.c);
}
}
I get the Out Put
new Object Created = 1
new Object Created = 2
new Object Created = 3
new Object Created = 4
new Object Created = 5
new Object Created = 6
new Object Created = 7
new Object Created = 8
new Object Created = 9
accept call in temp = 1
accept call in temp = 2
accept call in temp = 3
accept call in temp = 4
accept call 5
accept call 6
accept call 7
accept call 8
accept call 9
RESULT total Test Object created =9
I know this does not matter a lot unless you are processing a lots data that way.. but just wanted to know