In this article, we will see what is Supplier Functional Interface introduced in Java 8 using examples.
What is java.util.function.Supplier ?
Supplier is a functional interface with a single abstract method get(). This was introduced in Java 8.
@FunctionalInterface public class Supplier<T> {
public T get();
}
When to use a Supplier Functional Interface ?
A Supplier is used when you want to generate instances without taking any input.
How to use Supplier Functional Interface ?
We can use Supplier to return an instance of a Class as below :
Supplier<SomeClass> supplier = () -> new SomeClass();
We could also use constructor reference as follows :
Supplier<SomeClass> supplier = SomeClass::new;
Java 8 Supplier Example 1 :
Supplier<String> s1 = () -> "Hello"; System.out.println(s1.get());
Output :
Hello
Java 8 Supplier Example 2 :
Supplier<LocalDate> s1 = LocalDate::now; System.out.println(s1.get());
Output :
2017-05-16
Java 8 Supplier Example 3 :
package com.topjavatutorial; import java.util.function.Supplier; public class TestSupplier { public static void main(String[] args) { Person p1 = getPerson(() -> new Person("John")); System.out.println(p1.getName()); Person p2 = getPerson(Person::new); System.out.println(p2.getName()); } static Person getPerson(Supplier<Person> supplier) { Person p = supplier.get(); return p; } }
package com.topjavatutorial; public class Person { private String name; public Person(String name) { this.name = name; } public Person() { this.name = "Dummy"; } public String getName() { return name; } }
Output :
John
Dummy
Java 8 Primitive Supplier
Java 8 introduced following primitive Supplier functional interfaces :
IntSupplier : Supplier of int-valued results.
Example :
IntSupplier randomInt = new Random()::nextInt;
LongSupplier : Supplier of long-valued results.
DoubleSupplier : Supplier of double-valued results.
BooleanSupplier : Supplier of Boolean-valued results.
© 2017 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post
#