Java Functional Programming : 4. Consumer

This is the multi part series on Java Functional Programming


4. Consumer


The Consumer interface has a default method – andThen. It is used for chaining multiple Consumer objects.

Category
Consumer
Interface Definition
Consumer<T>
Abstract Method
void accept (T t)
Default Method
Consumer<T> andThen(Consumer<? super T> after)

Let’s look at the body of the default andThen method. It looks like this.


       default Consumer<T> andThen(Consumer<? super T> after) {
              Objects.requireNonNull(after);
              return (T t) -> { accept(t); after.accept(t); };
       }


The andThen method takes in a lambda expression as an input, executes the accept method and returns back the lambda expression. Taking the same example of the chair, here is how the method can be used.

      
Chair chair = Chair.createChair("My Brand", 100, true);
                          
Consumer<Chair> prBrand = (c) -> System.out.println(c.getBrand());
Consumer<Chair> prCost  = (c) -> System.out.println(c.getPrice());
//wholesale cost is 80% of the cost
Consumer<Chair> prWsCost = (c) -> System.out.println(Math.round(0.8*c.getPrice()));
             
// the andThen method chains multiple functionalities
// which can be executed at ones.
// Note that the input to the function is a lambda expression
prBrand.andThen(prCost).andThen(prWsCost).accept(chair);


When this code is executed, then the method is executed in the same order as defined. This is what gets printed on the console.
Chair Created ... !!
My Brand
100
80

The first line comes from creating the “Chair” and not by any lambda expression. This way, complex functionalities can be broken into smaller parts and chained. We could have defined all the three functionalities in a single lambda expression giving the same result. But I guess you’d have guessed by now, that this has an advantage of the order. You can order the functionalities according to your will, and maybe omit a few based upon the need of the program. This could help in organizing the program by functionalities and choose them within the methods based upon parameters or functional requirements.

<< Prev (The java.util.function Library) | Next (Predicate) >>

Comments

Popular posts from this blog

Java Generics - 7. Upper and Lower Bounds

Java Functional Programming : 3. The java.util.function Library

Java Generics - 3. Multiple bounding