引用对象的实例方法
小于 1 分钟函数式编程方法引用
格式
对象名::方法名
使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个对象的成员方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用对象的实例方法。
public static void main(String[] args) throws Throwable {
List<Author> authors = getAuthors();
StringBuilder sb = new StringBuilder();
authors.stream()
.map(author -> author.getAge())
.forEach(age -> sb.append(age));
System.out.println(sb);
}
使用方法引用:
public static void main(String[] args) throws Throwable {
List<Author> authors = getAuthors();
StringBuilder sb = new StringBuilder();
authors.stream()
.map(author -> author.getAge())
.forEach(sb::append);
System.out.println(sb);
}