Java method references¶
Java method references are a shorthand notation for lambda expressions, used to implement functional interfaces by referencing an existing method.^[600-developer__java__java8__java8.md] They are categorized primarily by the context of the method being referenced, such as static methods, instance methods, or constructors.
Syntax and types¶
The general syntax for a method reference is ClassName::MethodName or objectInstance::MethodName.^[600-developer__java__java8__java8.md] Based on the relationship between the caller and the method, there are four main types:
- Static method references (
ClassName::staticMethod): Used to reference static methods of a class.^[600-developer__java__java8__java8.md] - Instance method references of a specific object (
objectInstance::instanceMethod): Used when calling a method on a specific object instance.^[600-developer__java__java8__java8.md] - Instance method references of an arbitrary object (
ClassName::instanceMethod): Used when the method is invoked on an arbitrary object of a particular type (e.g.,Student::getScore).^[600-developer__java__java8__java8.md] - Constructor references (
ClassName::new): Used to reference a constructor, treating the object creation process as a method.^[600-developer__java__java8__java8.md]
Lambda equivalence¶
Method references serve as syntactic sugar for lambda expressions. For example, a lambda expression like (Student student) -> student.getScore() can be rewritten as the method reference Student::getScore.^[600-developer__java__java8__java8.md]
Constructor references¶
Constructor references allow for the creation of objects using functional interfaces like Supplier, Function, or BiFunction, depending on the number of constructor arguments.^[600-developer__java__java8__java8.md] For instance:
Supplier<Student> c1 = Student::newmaps to a no-argument constructor.^[600-developer__java__java8__java8.md]BiFunction<String, Integer, Student> c11 = Student::newmaps to a constructor accepting two arguments (e.g.,Stringandint).^[600-developer__java__java8__java8.md]
Examples in Collections and Streams¶
Method references are frequently used within the Java Stream API for data processing^[600-developer__java__java8__java8.md].
- Iteration: The
forEachmethod can accept a method reference (e.g.,students.forEach(Student::collide)).^[600-developer__java__java8__java8.md] - Mapping: When transforming data, method references can be used as the mapper function (e.g.,
students.stream().map(Student::getScore)).^[600-developer__java__java8__java8.md] - Sorting: They can be used to supply a comparator (e.g.,
students.sort(Student::compareStudentByScore)).^[600-developer__java__java8__java8.md]
Sources¶
600-developer__java__java8__java8.md