我正在尝试理解 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 不同,Lambda 本身就是一个对象,静态方法没有附加任何对象。那么它是如何满足这里的filter方法的呢。
谢谢
最佳答案
当你写的时候
intList.stream().filter( App::filterNosGrt3 ).forEach(System.out::println);
你正在有效地写作:
intList.stream().filter(e -> App.filterNosGrt3(e)).forEach(System.out::println);
这只是方法引用的一个特性。来自 Java method references tutorial :
You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.
...
The method reference
Person::compareByAge
is semantically the same as the lambda expression(a, b) -> Person.compareByAge(a, b)
. Each has the following characteristics:
- Its formal parameter list is copied from
Comparator<Person>.compare
, which is(Person, Person)
.- Its body calls the method
Person.compareByAge
.
关于java - 静态方法引用 Java 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41647906/