Dibyajyoti Behera
Dibyajyoti Behera

Reputation: 171

Why to use andThen in Consumer functional interface?

I want to perform one task one after another. We can do it in two ways.

First way is :

List<String> list = Arrays.asList("Name1","Name2","Name3");
list.forEach((obj)->{
    System.out.println(obj);  //task1
    System.out.println(obj.length()); //task2
});

Or we can do in this way as well :

List<String> list = Arrays.asList("Name1","Name2","Name3");
Consumer<String> c1 = (obj)-> System.out.println(obj); //task1
Consumer<String> c2 = (obj)-> System.out.println(obj.length()); //task2
list.forEach(c1.andThen(c2));

In both the cases we get the same result, so why do we use andThen in Consumer functional interface? Is there any advantage in using it?

Upvotes: 0

Views: 126

Answers (1)

prayagupadhyay
prayagupadhyay

Reputation: 31222

One of the idea behind functions (Function<A, B>) is that they are composable,

eg. g(f(x)) which is equivalent to f.andThen(g).apply(x) in java.

Defining one function or multiple functions depends on responsibility you want to give for each function.

For example you can have separate "function for incrementing a number" and "function for creating square of a number" that way you can re-use them when needed.

    Function<Integer, Integer> f = a -> a + 1;
    Function<Integer, Integer> g = a -> a * a;

    var  incrementAndSquare = f.andThen(g).apply(2); //9

    Function<Integer, Integer> h = a -> a - 1;

    var decrementAndSquare = h.andThen(g).apply(5); //16

Note: Consumer<A> in java is also a function Function<A, void> that returns void.

In your case if its just println maybe one function should be enough unless you need same function somewhere else.

If you are doing two "separate tasks", you might want to define separate functions. That makes the responsibility clearer, provides composibility, easy to test functions individually.

Upvotes: 2

Related Questions