What is supplier in Java 8?
As a name suggest, Supplier is a Functional Interface which does not take any arguments but produces a value.
It is part of java.util.function package and introduces in Java 8.
Suppliers are useful when we don’t need to supply any value and obtain a result at the same time.
Supplier is contains only one abstract method :
- get()
Return type is T - the type of results supplied by this supplier.
Lest see simple example of supplier interface.
Example 1 : Print random number using Supplier Interface
import java.util.function.Supplier;
public class SupplierDemo {
public static void main(String[] args) {
Supplier<Double> supplier1 = () -> Math.random();
Supplier<Integer> supplier2 = () -> (int)(Math.random()*10);
System.out.println("Random value from 0 to 1 : "+ supplier1.get());
System.out.println("Random value from 0 to 1 : "+ supplier1.get());
System.out.println("Random value from 0 to 9 : "+ supplier2.get());
System.out.println("Random value from 0 to 9 : "+ supplier2.get());
}
}Output :
Random value from 0 to 1 : 0.5275071504631775
Random value from 0 to 1 : 0.2566787022560659
Random value from 0 to 9 : 4
Random value from 0 to 9 : 8
In first supplier, we are getting random value between 0 to 1 only. And in second supplier, we are getting integer random value between 0 to 9.
As you can see, we does not pass any arguments it is only return result.
Example 2 : Print List of String and Integer using Supplier
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
public class SupplierDemo {
public static void main(String[] args) {
Supplier<List<String>> supplier1 = () -> List.of(
"Java", "JavaScript", "Python", "Php", "Angular", "C#", "C++");
Supplier<List<Integer>> supplier2 = () -> Arrays.asList(
1, 2, 3, 4, 5, 6, 7, 8);
System.out.println(supplier1.get());
System.out.println(supplier2.get());
}
}Output :
[Java, JavaScript, Python, Php, Angular, C#, C++]
[1, 2, 3, 4, 5, 6, 7, 8]
Happy Coding.
Other Java 8 articles :-
Comments
Post a Comment