The Supplier interface in Java is an in-built Functional interface introduced in version 8, and it is located in java.util.function package. It has only one method, a functional method T get() that takes no input but returns the output. Since it is a Functional Interface, we can implement it with a Lambda expression.
Supplier<T>
@FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); }
Implementing the Supplier interface in Java
Example 1:
class Test { public static void main(String[] args) { Supplier<String> supplier = () -> "Java"; System.out.println(supplier.get()); } }
Output: Java
Here, inside the braces <>, we specified which type is the output, and we used a Lambda expression to write the implementation of the Supplier interface. Calling the get() method, we are retrieving the result of the Lambda body.
Example 2:
Let’s create a User class:
class User { private String name; private String username; private String membershipType; private String address; public User(String name, String username, String membershipType, String address) { this.name = name; this.username = username; this.membershipType = membershipType; this.address = address; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", username='" + username + "} + \n"; } }
Now let’s create one method that returns a list of users and call it from the Supplier:
class Test { private static List<User> getAllUsers() { List<User> users = new ArrayList<>(); users.add(new User("John", "john123", "premium", "5th Avenue")); users.add(new User("Megan", "meganusr", "gold", "New Light Street")); users.add(new User("Steve", "steve1234", "regular", "New Street Avenue")); users.add(new User("Melissa", "mell1", "premium", "Ser Kingston Street")); return users; } public static void main(String[] args) { Supplier<List<User>> usersSupplier = () -> getAllUsers(); System.out.println("Getting the users: " + usersSupplier.get()); } }
Output: Getting the users: [User{name=’John’, username=’john123} + , User{name=’Megan’, username=’meganusr} + , User{name=’Steve’, username=’steve1234} + , User{name=’Melissa’, username=’mell1} + ]
I hope this tutorial was helpful to you. To learn more, check out other Java Functional Programming tutorials.