439,432 views
1 vote
1 vote
How to write your own consumer java.

User Fbielejec
by
2.3k points

1 Answer

25 votes
25 votes
import java.util.function.Consumer;
public class ConsumerInterfaceExample {
static void printMessage(String name){
System.out.println("Hello "+name);
}
static void printValue(int val){
System.out.println(val);
}
public static void main(String[] args) {
// Referring method to String type Consumer interface
Consumer consumer1 = ConsumerInterfaceExample::printMessage;
consumer1.accept("John"); // Calling Consumer method
// Referring method to Integer type Consumer interface
Consumer consumer2 = ConsumerInterfaceExample::printValue;
consumer2.accept(12); // Calling Consumer method
}
}
User Kotarak
by
3.3k points