java - 静态方法引用 Java 8

标签 java lambda java-8

我正在尝试理解 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/

相关文章:

java - 组合多个切入点 AspectJ 返回adviceDidNotMatch 警告

c# - 如何单步执行 lambda 表达式

node.js - lambda 中的 s3.getObject 不返回任何内容

java - 如何在Junit 5中注册TestExecutionListener并检测是否所有测试都执行

java - 执行清理并将异常传递给调用者

java - 拒绝 j_security_check 上的 GET 方法

java - 禁用 MessageDialog 中的按键

c# - 我可以在 lambda 表达式中调用函数吗?

java - 在按值排序的 map 中的条目周围检索固定数量的条目

java-8 - 使用身份组合器并行流减少