Junior — Middle
Explain the difference between the Consumer and Supplier interfaces in the context of working with streams or functional interfaces.
sobes.tech AI
Answer from AI
In Java, interfaces Consumer and Supplier are functional interfaces used for working with lambda expressions and streams.
-
Consumer<T>accepts an object of typeTand returns nothing. It is used when you need to perform an action with the given object, such as printing it or changing its state.Consumer<String> printer = s -> System.out.println(s); printer.accept("Hello"); // prints Hello -
Supplier<T>does not accept arguments but returns an object of typeT. It is used for generating or supplying values.Supplier<Double> randomSupplier = () -> Math.random(); double value = randomSupplier.get();
Thus, Consumer is a "consumer" of data, and Supplier is a "supplier" of data.