Java 8 - Method Reference
Method references in Java 8 allow you to pass references to methods as arguments to functions or constructors. They provide a concise and easy-to-read way to express lambda expressions that just call an existing method.
Method references are classified into four types:
- Reference to a static method
- Reference to an instance method of an object of a particular type
- Reference to an instance method of an arbitrary object of a particular type
- Reference to a constructor
Here is an example of each type:
Reference to a static method
1
2
List<String> words = Arrays.asList("one", "two", "three");
Collections.sort(words, String::compareToIgnoreCase);
In this example, we are calling the sort method on the Collections class, which takes a list of strings and a comparator. We want to use the compareToIgnoreCase method of the String class as the comparator, so we pass a reference to it using the String::compareToIgnoreCase syntax.
Reference to an instance method of an object of a particular type
1
2
3
4
String s = "hello";
int length = s.length();
Function<String, Integer> f = String::length;
In this example, we are calling the length method on a String object. We want to use the length method as a function that takes a String and returns an Integer, so we pass a reference to it using the String::length syntax.
Reference to an instance method of an arbitrary object of a particular type
1
2
3
List<String> words = Arrays.asList("one", "two", "three");
words.forEach(System.out::println);
In this example, we are calling the forEach method on a list of strings. We want to print each string to the console, so we pass a reference to the println method of the System.out object using the System.out::println syntax.
Reference to a constructor
1
2
3
Supplier<List<String>> supplier = ArrayList::new;
List<String> list = supplier.get();
In this example, we are creating a Supplier object that provides a new instance of an ArrayList whenever it is called. We pass a reference to the ArrayList constructor using the ArrayList::new syntax.
Conclusion
Method references provide a concise and easy-to-read way to express lambda expressions that just call an existing method. They make your code more readable and less error-prone, and they help you to write more expressive and maintainable code. If you are working with Java 8 or higher, method references are a powerful tool that you should add to your programming.