Java 8 方法引用
Posted 走在修行的大街上
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 8 方法引用相关的知识,希望对你有一定的参考价值。
Java 8 方法引用
There are four kinds of method references:
Kind | Example |
---|---|
Reference to a static method | ContainingClass::staticMethodName |
Reference to an instance method of a particular object | containingObject::instanceMethodName |
Reference to an instance method of an arbitrary object of a particular type | ContainingType::methodName |
Reference to a constructor | ClassName::new |
方法引用通过方法的名字来指向一个方法。
方法引用可以使语言的构造更紧凑简洁,减少冗余代码。
方法引用使用一对冒号 :: 。
下面,我们定义了 4 个方法作为例子来区分 Java 中 4 种不同方法的引用。
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
public class ComparisonProvider {
public int compareByName(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
public static int compareByAge(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
public static void main(String[] args) {
List<Person> roster = Person.createRoster();
Person[] rosterAsArray = roster.toArray(new Person[roster.size()]);
// 特定对象的实例方法引用: containingObject::instanceMethodName
ComparisonProvider myComparisonProvider = new ComparisonProvider();
System.out.println("排序前:" + Arrays.toString(rosterAsArray));
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);
System.out.println("排序后:" + Arrays.toString(rosterAsArray));
// 静态方法引用:ContainingClass::staticMethodName
System.out.println("排序前:" + Arrays.toString(rosterAsArray));
Arrays.sort(rosterAsArray, ComparisonProvider::compareByAge);
System.out.println("排序后:" + Arrays.toString(rosterAsArray));
// 特定类型的任意对象的实例方法的引用: ContainingType::methodName
String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" };
System.out.println("排序前:" + Arrays.toString(stringArray));
Arrays.sort(stringArray, String::compareToIgnoreCase);
System.out.println("排序后:" + Arrays.toString(stringArray));
// 构造器引用: ClassName::new
Person newPerson = Person.create(Person::new);
newPerson.setName("xiaocao");
newPerson.setBirthday(LocalDate.of(1995, 8, 20));
System.out.println(newPerson);
}
}
点击查看结果
排序前:[[Fred, 1980-06-20], [Jane, 1990-07-15], [George, 1991-08-13], [Bob, 2000-09-12]]
排序后:[[Bob, 2000-09-12], [Fred, 1980-06-20], [George, 1991-08-13], [Jane, 1990-07-15]]
排序前:[[Bob, 2000-09-12], [Fred, 1980-06-20], [George, 1991-08-13], [Jane, 1990-07-15]]
排序后:[[Fred, 1980-06-20], [Jane, 1990-07-15], [George, 1991-08-13], [Bob, 2000-09-12]]
排序前:[Barbara, James, Mary, John, Patricia, Robert, Michael, Linda]
排序后:[Barbara, James, John, Linda, Mary, Michael, Patricia, Robert]
[xiaocao, 1995-08-20]
参考链接:
- https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
- https://blog.csdn.net/yitian_66/article/details/81010434
以上是关于Java 8 方法引用的主要内容,如果未能解决你的问题,请参考以下文章