Method Reference - HolmesJJ/OOP-FP GitHub Wiki

Definition

Simplify existing methods in lambda expressions through method reference. The method reference is a Lambda expression, where the operator of the method reference is the double colon "::".

Introdction

Print each element in the ArrayList

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

/* Before Java 8 */
for (Integer e : list) {
    System.out.println(e);
}

/* From Java 8 */
list.forEach(e -> System.out.println(e));

// The content of the lambda expression just passes the parameter e to the println() method,
// so it can be further simplified
list.forEach(System.out::println);

Note:

  1. System.out::println is different from System.out.println()
  2. System.out::println can be regarded as a short form of lambda expression e -> System.out.println(e)
⚠️ **GitHub.com Fallback** ⚠️