欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

JAVA 中的匿名函数》学习指南

最编程 2024-03-11 13:50:21
...

在这篇博客中,我们将学习什么是 匿名函数和匿名函数的类型。所以,现在我开始介绍Java中的匿名函数,我们将逐一深入了解它,并探索它的每个概念。

如果你指的是匿名函数(function literal,lambda abstraction),那么你使用的是Java 8版本。

什么是匿名函数?

匿名函数是一个不与标识符绑定的函数。因为,这些是嵌套函数的一种形式,允许访问包含函数范围内的变量(非本地函数)。所以,这意味着匿名函数需要用闭包来实现。简单地说,lambda是一个匿名函数,可以用简洁的方式来传递。

或者说

匿名函数(function literal,lambda abstraction抽象,lambda函数,lambda expressionor block)是没有绑定 标识符函数定义。匿名函数通常是被传递给高阶函数的参数,或者用于构造需要返回函数的高阶函数的结果。

另外,一个lambda表达式代表一个匿名函数,它由一组参数、一个lambda操作符(->)和一个函数体组成。

返回类型

  1. 当有一条语句时,匿名函数的返回类型与主体表达式的返回类型相同。
  2. 当有一个以上的语句用大括号括起来时,匿名函数的返回类型与代码块中返回的值的类型相同,如果没有返回,则为void。

例子

  • 零参数

() -> System.out.println(" No Parameters " )。

  • 一个参数

(参数) -> System.out.println("一个参数是 : " + 参数)。

或不带括号;参数->参数(身份函数例子)

  • 多个参数

(parameter1, parameter2) -> parameter1 + parameter2。

  • 参数类型

(int a, String name) -> System.out.println("id:" + a + " name:" + name)。

  • 代码块

(parameter1, parameter2) -> { return parameter1 + parameter2; }

  • 嵌套的lambda表达式 :两个嵌套的表达式,第一个是封闭的
(id, defaultCost) -> {

  Optional<Product> product = productList.stream().filter(p -> p.getId() == id).findFirst();

  return product.map(p -> p.getCost()).orElse(defaultCost);

 }

拷贝

  • 作为对象。lambda表达式被推荐给变量,最后它被它执行的接口策略所召唤
public interface Comparator {
    public boolean compare (int x, int y);
 }

 Comparator myComparator = (x, y) -> return x > y;
 boolean result = myComparator.compare(5, 3);

拷贝

所以,我们可以把它联系起来。

Arrays.sort ( customer_Array, new Comparator (<Customer>( ) {

    @Override
    public int compare ( Customer c1, Customer c2 ) {
        return c1.getAge ( ) - c2.getAge ( ) ;
    }
});

复制

所以,它变成->

Arrays.sort ( customer_Array, (c1,c2) -> c1.getAge( ) - c2.getAge ( ) );

复制

Lambda表达式作为功能接口:

除了一个或多个默认或静态方法外,只包含一个抽象方法的接口。

 public class Calculator {
    interface IntegerMath {
        int operation (int x, int y) ;

        default IntegerMath swap ( ) {
          return (x, y) -> operation ( y, x ) ;
        }
    }
    private static int apply ( int x,   int y,   IntegerMath op) {
        return op.operation (x, y) ;
    }

    public static void main (String[] args) {
        IntegerMath addition = (x, y) -> x + y;
        IntegerMath subtraction = (x, y) -> x - y;
        System.out.println("50 + 12= " + apply (50, 12, addition ));
        System.out.println("40 - 10 = " + apply (40, 10, subtraction ));
        System.out.println("30 - 15 = " + apply (30, 15, subtraction.swap( )));    
    }

复制代码

上面的输出:

 /usr/lib/jvm/java-1.11.0-openjdk-amd64/bin/java -javaagent:/snap/intellij-idea-community/

 50 + 12 =  62
 40 - 10  =  30
 30 - 15  = -15

 Process finished with exit code 0

复制

所以,这里IntegerMath是一个功能接口,它有默认的swap方法和实现IntegerMath的Lambda表达式,并传递给apply ( ) 方法。

闭包

这些是在包含绑定变量的环境中评估的函数,下面的例子在一个匿名函数中绑定了变量 "阈值",将输入与阈值进行比较。

def comp (threshold) :
    return lambda x: x < threshold

拷贝

作为一种比较函数的生成器,我们可以使用Closures。

>>> func_a  =  comp ( 10 )
>>> func_b  = comp ( 20 )

>>> print (func_a ( 5 ),  func_a ( 8 ),  func_a ( 13 ),  func_a ( 21 ) )
True   True   False   False

>>> print (func_b ( 5 ),  func_b ( 8 ),  func_b ( 13 ),  func_b ( 21 ) )
True   True   True   False 

复制代码

为每一个可能的比较函数创建一个函数是不切实际的,而且把阈值保留下来继续使用也可能太不方便了。无论使用闭包的原因是什么,匿名函数是包含进行比较的功能的实体。

策划:

凝结是改变一个函数的过程,使其不再接受多个输入,而是接受一个单一的输入并返回一个接受第二个输入的函数,以此类推。此外,一个执行任何整数除法的函数被转化为执行除以一个设定的整数的函数。

>>>  def divide (x, y) :
          return x / y

>>>  def divisor (d) :
          return lambda x: divide (x, d)

>>>  half  = divisor ( 2 )
>>>  third = divisor ( 3 )

>>>  print ( half (22), third (41) )
        11.0    13.666666666666667

>>> print ( half ( 60 ), third ( 52 ) )
        30.0     17.333333333333334

复制代码

当使用匿名函数时,它也许并不常见。当利用神秘函数时,它也许并不正常。因此,在上面的例子中,函数divisor生成了具有指定除数的函数。同样地,函数half和three curry是具有固定除数的除法函数。

除数函数还通过绑定变量d形成一个闭包。

推荐阅读