Junior — Middle
Explain the differences between the Supplier and Consumer interfaces in the context of data transfer and their usage.
sobes.tech AI
Answer from AI
In Java, the interfaces Supplier and Consumer are part of functional interfaces and are used for different purposes:
-
Supplier<T> — this is a data provider. It does not accept input parameters but returns an object of type
T. It is used when you need to obtain data without input arguments. -
Consumer<T> — this is a data consumer. It accepts an object of type
Tand returns nothing. It is used for processing or consuming data.
Example:
Supplier<String> supplier = () -> "Hello";
Consumer<String> consumer = s -> System.out.println(s);
String value = supplier.get(); // Gets the string "Hello"
consumer.accept(value); // Prints the string to the console
Thus, Supplier generates or provides data, and Consumer accepts and processes it.