引用类的静态方法
小于 1 分钟函数式编程方法引用
格式
类名::方法名
使用前提
如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的静态方法。并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个静态方法中,这个时候我们就可以引用类的静态方法。
public static void main(String[] args) throws Throwable {
List<Author> authors = getAuthors();
List<String> ages = authors.stream()
.map(Author::getAge)
.distinct()
.map(age -> String.valueOf(age))
.collect(Collectors.toList());
System.out.println(ages);
}
valueOf是String的静态方法,也满足方法引用的前提。这里我们可以直接使用方法引用:
public static void main(String[] args) throws Throwable {
List<Author> authors = getAuthors();
List<String> ages = authors.stream()
.map(Author::getAge)
.distinct()
.map(String::valueOf) // 引用类的静态方法
.collect(Collectors.toList());
System.out.println(ages);
}