GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||
GeezerVison is showing docs.oracle.com — Method References (The Java™ Tutorials > Learning the Java Language > Classes and Objects) Documentation
The Java™ Tutorials
Hide TOC
Method References
Trail: Learning the Java Language
Lesson: Classes and Objects Section: Nested Classes Subsection: Lambda Expressions The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. Method ReferencesYou use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name. Consider again the
public class Person {
// ...
LocalDate birthday;
public int getAge() {
// ...
}
public LocalDate getBirthday() {
return birthday;
}
public static int compareByAge(Person a, Person b) {
return a.birthday.compareTo(b.birthday);
}
// ...
}
Suppose that the members of your social networking application are contained in an array, and you want to sort the array by age. You could use the following code (find the code excerpts described in this section in the example
Person[] rosterAsArray = roster.toArray(new Person[roster.size()]);
class PersonAgeComparator implements Comparator<Person> {
public int compare(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
Arrays.sort(rosterAsArray, new PersonAgeComparator());
The method signature of this invocation of static <T> void sort(T[] a, Comparator<? super T> c) Notice that the interface Arrays.sort(rosterAsArray,
(Person a, Person b) -> {
return a.getBirthday().compareTo(b.getBirthday());
}
);
However, this method to compare the birth dates of two Arrays.sort(rosterAsArray,
(a, b) -> Person.compareByAge(a, b)
);
Because this lambda expression invokes an existing method, you can use a method reference instead of a lambda expression: Arrays.sort(rosterAsArray, Person::compareByAge); The method reference
Kinds of Method ReferencesThere are four kinds of method references:
The following example,
import java.util.function.BiFunction;
public class MethodReferencesExamples {
public static <T> T mergeThings(T a, T b, BiFunction<T, T, T> merger) {
return merger.apply(a, b);
}
public static String appendStrings(String a, String b) {
return a + b;
}
public String appendStrings2(String a, String b) {
return a + b;
}
public static void main(String[] args) {
MethodReferencesExamples myApp = new MethodReferencesExamples();
// Calling the method mergeThings with a lambda expression
System.out.println(MethodReferencesExamples.
mergeThings("Hello ", "World!", (a, b) -> a + b));
// Reference to a static method
System.out.println(MethodReferencesExamples.
mergeThings("Hello ", "World!", MethodReferencesExamples::appendStrings));
// Reference to an instance method of a particular object
System.out.println(MethodReferencesExamples.
mergeThings("Hello ", "World!", myApp::appendStrings2));
// Reference to an instance method of an arbitrary object of a
// particular type
System.out.println(MethodReferencesExamples.
mergeThings("Hello ", "World!", String::concat));
}
}
All the
Reference to a Static MethodThe method references Reference to an Instance Method of a Particular ObjectThe following is an example of a reference to an instance method of a particular object: class ComparisonProvider {
public int compareByName(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
public int compareByAge(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);
The method reference Similarly, the method reference Reference to an Instance Method of an Arbitrary Object of a Particular TypeThe following is an example of a reference to an instance method of an arbitrary object of a particular type: String[] stringArray = { "Barbara", "James", "Mary", "John",
"Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);
The equivalent lambda expression for the method reference Similarly, the method reference Reference to a ConstructorYou can reference a constructor in the same way as a static method by using the name public static <T, SOURCE extends Collection<T>, DEST extends Collection<T>>
DEST transferElements(
SOURCE sourceCollection,
Supplier<DEST> collectionFactory) {
DEST result = collectionFactory.get();
for (T t : sourceCollection) {
result.add(t);
}
return result;
}
The functional interface Set<Person> rosterSetLambda =
transferElements(roster, () -> { return new HashSet<>(); });
You can use a constructor reference in place of the lambda expression as follows: Set<Person> rosterSet = transferElements(roster, HashSet::new); The Java compiler infers that you want to create a Set<Person> rosterSet = transferElements(roster, HashSet<Person>::new); About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.
Previous page: Lambda Expressions
Next page: When to Use Nested Classes, Local Classes, Anonymous Classes, and Lambda Expressions | |||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |