Java - Use static method reference as data Supplier

Introduction

Person class contains a getPersons() static method as shown:

static List<Person> getPersons()

The method takes no argument and returns a List<Person>.

Supplier<T> represents a function that takes no argument and returns a result of type T.

The following code uses the method reference Person::getPersons as a Supplier<List<Person>>:

Supplier<List<Person>>supplier = Person::getPersons;
List<Person> personList = supplier.get();
FunctionUtil.forEach(personList, p -> System.out.println(p));

Demo

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class Main {
  public static void main(String[] args) {
    Supplier<List<Person>> supplier = Person::getPersons;
    List<Person> personList = supplier.get();
    forEach(personList, p -> System.out.println(p));

  }//from  w w  w  .ja  v a2 s. co m
  public static <T> void forEach(List<T> list, Consumer<? super T> action) {
    for (T item : list) {
      action.accept(item);
    }
  }
}

enum Gender {
  MALE, FEMALE
}

class Person {
  private String firstName;
  private String lastName;
  private LocalDate dob;
  private Gender gender;

  public Person(String firstName, String lastName, LocalDate dob, Gender gender) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.dob = dob;
    this.gender = gender;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public LocalDate getDob() {
    return dob;
  }

  public void setDob(LocalDate dob) {
    this.dob = dob;
  }

  public Gender getGender() {
    return gender;
  }

  public void setGender(Gender gender) {
    this.gender = gender;
  }

  @Override
  public String toString() {
    return firstName + " " + lastName + ", " + gender + ", " + dob;
  }

  // A utility method
  public static List<Person> getPersons() {
    ArrayList<Person> list = new ArrayList<>();
    list.add(new Person("A", "D", LocalDate.of(1975, 1, 20), Gender.MALE));
    list.add(new Person("B", "E", LocalDate.of(1965, 9, 12), Gender.MALE));
    list.add(new Person("C", "D", LocalDate.of(1970, 9, 12), Gender.FEMALE));
    return list;
  }
}

Result

Related Topic