The consumer interface of the functional interface accepts only one single argument without any return value. The consumer interface has no return value. It contains an abstract accept() and a default andThen() method. It can be used as the assignment target for a lambda expression or method reference.
import java.util.function.*; public class ConsumerInterfaceAcceptExample{ static void welcomeGreeting (
String
name){ System.out.println( "Welcome "+name ); } static void showAge (int age){ System.out.println( "Age is "+age ); } static void showSalary (int sal){ System.out.println( "Salary is "+sal ); } public static void main(String[] args) { 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 Age is 30 Salary is 20000
import java.util.function.Consumer; public class ConsumerInterfaceAndThenExample{ public static void main(String[] args) { //method reference Consumer<
String
> consumer = s -> System.out.println( "Welcome "+s ); Consumer<
String
> consumer2 = s -> System.out.println( "Welcome "+s+ "to the World!" ); Consumer<
String
> consumer2 = consumer.andThen( consumer2 ); // Calling Consumer method consumer.accept( "Rahul" ); } } Output: Welcome Rahul Welcome Rahul to the World!
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 );