Java8 | Supplier
2 min readDec 25, 2020
What we need to know about Supplier
- Supplier is a functional interface;
@FunctionalInterface
public interface Supplier<T>
- It takes no arguments and returns a result of type T.
T get();
- Also, through Stream’s generate method we can generate an infinite sequential stream where the supplier generates each element.
public static<T> Stream<T> generate(Supplier<? extends T> s)
- In scenarios where we expect an output without input in any process, we can use the functional interface of Supplier <T> without having to redefine it each time.
Let’s investigate code examples :)
Use of supplier in the get method
- We used supplier get method of the Supplier interface and then it takes no argument and returns T.
Use of supplier in Stream’s generate method
Let’s say we want to generate 5 random numbers between 0 to 20
- We created supplier01 and created Random between 0 to 20.
- 6. line, we used Stream’s generate method and also gave 5 as the limit.
- 10. line, we took 2 numbers because of we used filter(Predicate<T>)
- 12. we can use it like on the line if we create a static method.
Use of supplier in LocalDate
Let’s use static LocalDateTime in different ways
Another Stream’s generate method and returns a Supplier example;
Use of supplier in orElseGet
- orElseGet (): returns the value if it exists, otherwise it calls another and returns the result of its call
public T orElseGet(Supplier<? extends T> other)
Another example;
- If a null object comes from the database when we want to get data on the database, we can call a method or return an empty object.
- We will detail the investigation about Optional in Optional blog.
Thank you for your time :)
Github: Supplier
References: