andThen() Method Example In Java

The andThen() and accept() methods are methods of Consumer Interfaces.

Consumer Interface Methods.
  1. void accept(T t)
  2. The accept() method takes as input the type T and returns no value. This is the single abstract method of Consumer. It accepts a single generic argument of type T and returns nothing (i.e. void). This is the method that's implemented by a lambda expression or method reference.
  3. andThen(Consumer after)
  4. The andThen() is a default method. In other words, it has an implementation and is thus non-abstract. The method accepts a Consumer and returns another Consumer.

Example of andThen() method of Consumer Interface

  1. The andThen() method allows multiple Consumer operations sequentialy.
  2. The andThen() method accepts a Consumer and returns another Consumer.
  3. If the original Consumer (the one calling andThen()) throws an exception, the after Consumer will not be executed.
import java.util.function.Consumer;

public class ConsumerInterfaceExample{
  public static void main(String[] args) {
   //method reference 
   Consumer<String> consumer1 =
      s -> System.out.println( "Welcome "+s );

   Consumer<String> consumer2 =
      s -> System.out.println( "Welcome "+s+ "to the World!" );

   Consumer<String> consumer2 =
      consumer1.andThen( consumer2 );

   // Calling Consumer method
   consumer1.accept( "Tejas" ); 

    }
}


Output:
    Welcome Tejas
    Welcome Tejas to the World!

Example of accept() method of Consumer Interface

import java.util.function.Consumer;

public class ConsumerInterfaceExample{
 static void  welcomeGreeting (String name){
    System.out.println( "Welcome "+name );
 }
 static void showAge (int age){
    System.out.println( "Your age is "+age );
 }
 static void showSalary (int sal){
    System.out.println( "Your salary is "+sal );
 }

 public static void main( String[] args) {
    //method reference 
    Consumer<String> consumer1 =
        ConsumerInterfaceExample :: welcomeGreeting;
        // Calling Consumer method
        consumer1.accept( "Tejas" );

    //method reference    
    Consumer<Integer> consumer2 = 
        ConsumerInterfaceExample::showAge;  
        // Calling Consumer method
        consumer2.accept( 30 );

    //method reference
    Consumer<Integer> consumer2 = 
        ConsumerInterfaceExample :: showSalary;
        // Calling Consumer method 
        consumer2.accept( 20000 );
   
  }
}


Output:
    Welcome Tejas
    Your age is 30
    Your salary is 20000

Bi-Consumer

The different between Consumer and Bi-Consumer is Consumer takes only one argument, but Bi-Consumer interface takes two arguments. Both, Consumer and Bi-Consumer have no return value. It is used in iterating through the entries of the map.

 BiConsumer<String,String> foo = (a, b) -> System.out.println( a + b );