Mark As Completed Discussion

Method References

In Java 8, a method reference is a shorthand notation for a lambda expression that calls a specific method.

Method references can be used when the lambda expression simply calls an existing method without doing any additional computation or modification. This allows for cleaner and more concise code.

Let's take a look at an example using method references:

TEXT/X-JAVA
1import java.util.ArrayList;
2import java.util.List;
3
4public class MethodReferencesExample {
5
6  public static void main(String[] args) {
7    List<String> fruits = new ArrayList<>();
8    fruits.add("Apple");
9    fruits.add("Banana");
10    fruits.add("Orange");
11    
12    // Method references example
13    fruits.forEach(System.out::println);
14  }
15}

In this example, we have a list of fruits and we want to print each fruit to the console. Instead of using a lambda expression, we can use a method reference System.out::println as a shorthand notation. This method reference refers to the static method println of the System.out object.

Method references offer a more concise and readable way to express certain lambda expressions, making our code easier to understand and maintain.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment