Supplier and Consumer
Produce and consume values.
What Supplier Does
Supplier<T> takes no arguments and produces a value of type T.
- Its method is
T get(). - Perfect for lazy or deferred value creation.
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier<String> greeting = () -> "Hello!";
System.out.println(greeting.get());
}
}Suppliers Are Lazy
The code inside a Supplier runs only when get is called. This makes suppliers ideal for expensive defaults you may never need.
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier<Integer> expensive = () -> {
System.out.println("computing...");
return 42;
};
System.out.println("before get");
System.out.println(expensive.get());
}
}All lessons in this course
- Function and BiFunction
- Supplier and Consumer
- Predicate and Composition
- Custom Functional Interfaces