Sobes.tech
Junior

What is the difference between Supplier and Consumer in Java?

sobes.tech AI

Answer from AI

In Java, Supplier and Consumer are functional interfaces from the java.util.function package, used for working with lambda expressions and functional programming.

  • Supplier<T> is a provider that does not take arguments but returns an object of type T. It is used when you need to obtain or generate a value without input data.

  • Consumer<T> is a consumer that accepts an object of type T and returns nothing. It is used to perform operations on the object, such as output or state modification.

Example:

Supplier<String> supplier = () -> "Hello, World!";
String result = supplier.get(); // returns "Hello, World!"

Consumer<String> consumer = s -> System.out.println(s);
consumer.accept(result); // outputs "Hello, World!"

Thus, Supplier generates data, and Consumer consumes it.