Java Stream How to - Use constructor Reference








Question

We would like to know how to use constructor Reference.

Answer

public class Main {
/*from   w w  w  . j a va2  s . c o  m*/
  public static void main(String[] args) {

    PersonFactory<Person> personFactory = Person::new;
    Person person = personFactory.create("Firstname", "Lastname");
    System.out.println(person.firstName);
    System.out.println(person.lastName);


  }
}
@FunctionalInterface
interface PersonFactory<P extends Person> {
   public P create(String firstName, String lastname);
}

class Person {

  final String firstName;
  final String lastName;

  Person(String firstName, String lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
  }
}

The code above generates the following result.