Java 8 Supplier examples

In this post, we are going to see about java 8 Supplier interface.
Supplier is functional interface which does not take any argument and produces result of type T.It has a functional method called T get() As Supplier is functional interface, so it can be used as assignment target for lambda expressions.

Here is source code of Java 8 supplier interface.


package java.util.function;
/**
* Represents a supplier of results.
*
* <p>There is no requirement that a new or distinct result be returned each
* time the supplier is invoked.
*
* <p>This is a <a href=”package-summary.html”>functional interface</a>
* whose functional method is {@link #get()}.
*
* @param <T> the type of results supplied by this supplier
*
* @since 1.8
*/
@FunctionalInterface
public interface Supplier<T> {
    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}
 

Java 8 Supplier example

Lets use supplier interface to print String:

import java.util.function.Supplier;
 
public class Java8SupplierExample {
 
public static void main(String[] args) {
 
  Supplier<String> supplier= ()-> “Arpit”;
  System.out.println(supplier.get());
}
}

It is simple use of supplier interface to get String object. When you run above program, you will get below output:Arpit

Let’s create another example using custom class Student.We will use supplier to supply new Student object.Student.java

public class Student {
 
    private int id;
    private String name;
    private String gender;
    private int age;
 
    public Student(int id, String name, String gender, int age) {
        super();
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.age = age;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getGender() {
        return gender;
    }
 
    public void setGender(String gender) {
        this.gender = gender;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    @Override
    public String toString() {
        return “Student [id=” + id + “, name=” + name + “, gender=” + gender + “, age=” + age + “]”;
    }
}
 

Now lets create Supplier object which will be used to supply new Student object.

import java.util.function.Supplier;
 
public class Java8SupplierExample {
 
    public static void main(String[] args) {
 
        Supplier studentSupplier = () -> new Student(1, “Arpit”, “M”, 19);
        Student student = studentSupplier.get();
        System.out.println(student);
    }
}

Use of supplier in Stream’s generate method

If you observe signature of Stream’s generate method, you will notice that it takes supplier as argument.

123 public static<T> Stream<T> generate(Supplier<T> s) 

Stream's generate method returns an infinite sequential stream where supplier generates each element.
Let’s say you want to generate 5 random numbers between 0 to 10.

 import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Stream; 
public class Java8SupplierExample {    
  public static void main(String[] args) {         
Supplier<Integer> randomNumbersSupp=() -> new Random().nextInt(10);       
 Stream.generate(randomNumbersSupp).limit(5).forEach(System.out::println);    } } 

Output:8
3
5
2
2

As you want see we have used supplier as () -&gt; new Random().nextInt(10) to generate random numbers. limit(5) is used to limit the stream to 5 elements only and also used Java 8 foreach loop to print elements of the Stream.
That’s all about Java 8 Supplier example.

Popular posts from this blog

Window function in PySpark with Joins example using 2 Dataframes (inner join)

Complex SQL: fetch the users who logged in consecutively 3 or more times (lead perfect example)

Credit Card Data Analysis using PySpark (how to use auto broadcast join after disabling it)