How can I write an anonymous function in Java?

后端 未结 5 1198
无人及你
无人及你 2020-12-22 23:15

Is it even possible?

5条回答
  •  情书的邮戳
    2020-12-23 00:01

    With the introduction of lambda expression in Java 8 you can now have anonymous methods.

    Say I have a class Alpha and I want to filter Alphas on a specific condition. To do this you can use a Predicate. This is a functional interface which has a method test that accepts an Alpha and returns a boolean.

    Assuming that the filter method has this signature:

    List filter(Predicate filterPredicate)
    

    With the old anonymous class solution you would need to something like:

    filter(new Predicate() {
       boolean test(Alpha alpha) {
          return alpha.centauri > 1;
       }
    });
    

    With the Java 8 lambdas you can do:

    filter(alpha -> alpha.centauri > 1);
    

    For more detailed information see the Lambda Expressions tutorial

提交回复
热议问题