Java Lambda - Supplier example








Supplier represents a supplier of results.

Method

  1. Supplier get

Example

The following example shows how to use Supplier.

import java.util.function.Supplier;
/* ww  w .  ja  v a 2 s  .  c om*/
public class Main {

  public static void main(String[] args) {
    Supplier<String> i  = ()-> "java2s.com";
    
    System.out.println(i.get());
  }
}

The code above generates the following result.





Example 2

The following code shows how to pass Supplier as parameter.

/*  w  w w  .j a  va2 s.  c om*/
import java.util.Objects;
import java.util.function.Supplier;

public class Main {
    public static SunPower produce(Supplier<SunPower> supp) {
        return supp.get();
    }
    public static void main(String[] args) {
        SunPower power = new SunPower();

        SunPower p1 = produce(() -> power);
        SunPower p2 = produce(() -> power);

        System.out.println("Check the same object? " + Objects.equals(p1, p2));
    }
} 

class SunPower {

  public SunPower() {
      System.out.println("Sun Power initialized..");
  }
}

The code above generates the following result.





Example 3

The following code shows how to use Constructor as method reference for Supplier.

/*from  w  w  w .  java2s  .  c o  m*/
import java.util.function.Supplier;

public class Main {
  public static void main(String[] args) {
    System.out.println(maker(Employee::new));
  }

  private static Employee maker(Supplier<Employee> fx) {
    return fx.get();
  }
}

class Employee {
  @Override
  public String toString() {
    return "A EMPLOYEE";
  }
}

The code above generates the following result.

Example 4

The following code shows how to assign user defined function to Supplier with method reference.

//  w  w  w. j a v a  2 s  .  com
import java.util.function.Supplier;

public class Main {
  public static void main(String[] args) {
    Supplier<Student> studentGenerator = Main::employeeMaker;

    for (int i = 0; i < 10; i++) {
      System.out.println("#" + i + ": " + studentGenerator.get());
    }
  }

  public static Student employeeMaker() {
    return new Student("A",2);
  }

}

class Student {
  public String name;
  public double gpa;

  Student(String name, double g) {
    this.name = name;
    this.gpa = g;
  }

  @Override
  public String toString() {
    return name + ": " + gpa;
  }
}

The code above generates the following result.