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