Java - Instance Method References Bound Receiver

Introduction

For a bound receiver, use the objectRef.instanceMethod syntax. Consider the following snippet of code:

Supplier<Integer> supplier = () -> "abc".length();
System.out.println(supplier.get());

You can rewrite this statement using an instance method reference with the "abc" object as the bound receiver using a Supplier<Integer> as the target type as shown:

Supplier<Integer> supplier = "abc"::length;
System.out.println(supplier.get());

The following code represents a Consumer<String> that takes a String as an argument and returns void:

Consumer<String> consumer = str -> System.out.println(str);
consumer.accept("Hello");

The above lambda expression invokes the println() method on the System.out object.

It can be rewritten using a method reference with System.out as the bound receiver, as shown:

Consumer<String> consumer = System.out::println;
consumer.accept("Hello");

The following code uses the method reference System.out::println to print the list of persons.

Demo

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

public class Main {
  public static void main(String[] args) {
    List<Person> list = Person.getPersons();
    forEach(list, System.out::println);

  }//  w w w . ja v a 2  s  .c  o  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