我正试图把我的注意力集中在Java 8的概念上。在方法引用的上下文中,我想知道在我的示例中接受‘谓词’对象的流过滤器方法如何也可以接受同一个类中的静态方法。下面的例子。
public class App
{
public static void main( String[] args )
{
List<Integer> intList = Arrays.asList(1,2,3,4,5);
intList.stream().filter( e -> e > 3 ).forEach(System.out::println);
intList.stream().filter( App::filterNosGrt3 ).forEach(System.out::println);
}
public static boolean filterNosGrt3(Integer no)
{
if(no>3)
return true;
else
return false;
}
}让我困惑的不像Lambda,它本身就是一个对象,静态方法没有对象附加到它。那么它是如何满足这里的过滤方法的。
谢谢
发布于 2017-01-14 08:01:19
当你写
intList.stream().filter( App::filterNosGrt3 ).forEach(System.out::println);你实际上是在写:
intList.stream().filter(e -> App.filterNosGrt3(e)).forEach(System.out::println);这只是方法引用的一个特性。来自Java方法参考教程
使用lambda表达式创建匿名方法。然而,有时lambda表达式只会调用现有的方法。在这些情况下,按名称引用现有方法通常更清楚。方法引用使您能够做到这一点;对于已经有名称的方法,它们是紧凑的、易于阅读的lambda表达式。 ..。 方法引用
Person::compareByAge在语义上与lambda表达式(a, b) -> Person.compareByAge(a, b)相同。每一项都具有以下特点:
Comparator<Person>.compare (即(Person, Person) )复制的。Person.compareByAge。https://stackoverflow.com/questions/41647906
复制相似问题