Consumer that returns nothing in java
- User
Consumer that returns nothing in java
- Assistant
In Java, the
Consumerfunctional interface is used to define an operation that takes in an input parameter and performs some action, without returning anything. It has a single abstract method calledaccept(), which takes in an input and does not return anything.Here's an example of a
Consumerthat takes in an integer and simply prints it out:import java.util.function.Consumer; public class ExampleConsumer { public static void main(String[] args) { Consumer<Integer> printNumber = (num) -> System.out.println(num); printNumber.accept(10); // Output: 10 printNumber.accept(20); // Output: 20 } }In this example, the
ConsumernamedprintNumbertakes in an integer and prints it out using theSystem.out.println()method inside theaccept()method. It does not return any value.The
Consumerfunctional interface in Java is commonly used in scenarios where you need to perform an action that doesn't require a return value, such as printing, logging, or side-effect operations.