Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Consumer Interface

It is a functional interface present in java.util.function package.
It contains an abstract accept() and a default and Then() method.
It can be used as the assignment target for a lambda expression or method reference.
The Consumer Interface accepts a single argument.
It does not return any result.

Java Consumer Interface Example 1
import java.util.function.Consumer;
public class ConsumerInterfaceExample1
{ 
	static void print(String name) 
	{
		System.out.println("Hello "+name);
	}
	static void show(int val)
	{
		System.out.println(val);
	}
	public static void main(String[] args)
	{
		// Referring method to String type Consumer interface
		consumer1.accept("Sanghamitra"); // Calling Consumer method
		Consumer< String > consumer1 = ConsumerInterfaceExample1::print;
		// Referring method to Integer type Consumer interface
		Consumer consumer2 = ConsumerInterfaceExample1::show;
		consumer2.accept(100); // Calling Consumer method
	}
}

OUTPUT:
Hello Sanghamitra
100

JAVA Consumer Interface Example2
importjava.util.ArrayList;
importjava.util.List;
importjava.util.function.Consumer;
public class ConsumerInterfaceExample2
{ 
	static void addList(List l) 
	{
		// Return sum of list values
		int result = l.stream()
		.mapToInt(Integer::intValue)
		.sum();
		System.out.println("Sum of values: "+result);
	}
	public static void main(String[] args)
	{
		List list = new ArrayList();
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);
		 // Referring method to String type Consumer interface
		Consumer> consumer = ConsumerInterfaceExample::addList;
		consumer.accept(list);// Calling Consumer method
	}
}

OUTPUT:
Sum of values: 10

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext