Java 8 Supplier

Supplier

A Supplier is a simple interface which indicates that this implementation is a supplier of results. This interface, however, does not enforce any restrictions that supplier implementation needs to return a different result on each invocation.

The supplier has only one method get() and does not have any other default and static methods. 

@Test
public void supplier(){
Supplier<Double> doubleSupplier1 = () -> Math.random();
DoubleSupplier doubleSupplier2 = Math::random;

System.out.println(doubleSupplier1.get());
System.out.println(doubleSupplier2.getAsDouble());
The supplier interface has its primitive variants such as IntSupplier, DoubleSupplier and 
so on as shown below. Note that the method name is get() for the generic supplier interface. However, for the primitive variants, it is as per the primitive type.

IntSupplier int getAsInt();
DoubleSupplier double getAsDouble();
LongSupplier long getAsLong();
BooleanSupplier boolean getAsBoolean();

One of the primary usage of this interface to enable deferred execution. This means delaying the execution until it is needed. For example, Optional class has a method named orElseGet. This method is triggered if optional does not have data. This is demonstrated below:

@Test
public void supplierWithOptional(){
Supplier<Double> doubleSupplier = () -> Math.random();
Optional<Double> optionalDouble = Optional.empty();
System.out.println(optionalDouble.orElseGet(doubleSupplier));
}

Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

Junit Mockito and Power Mockito

Important Linux Commands