JAVA 中的匿名函数》学习指南
在这篇博客中,我们将学习什么是 匿名函数和匿名函数的类型。所以,现在我开始介绍Java中的匿名函数,我们将逐一深入了解它,并探索它的每个概念。
如果你指的是匿名函数(function literal,lambda abstraction),那么你使用的是Java 8版本。
什么是匿名函数?
匿名函数是一个不与标识符绑定的函数。因为,这些是嵌套函数的一种形式,允许访问包含函数范围内的变量(非本地函数)。所以,这意味着匿名函数需要用闭包来实现。简单地说,lambda是一个匿名函数,可以用简洁的方式来传递。
或者说
匿名函数(function literal,lambda abstraction抽象,lambda函数,lambda expressionor block)是没有绑定 标识符的函数定义。匿名函数通常是被传递给高阶函数的参数,或者用于构造需要返回函数的高阶函数的结果。
另外,一个lambda表达式代表一个匿名函数,它由一组参数、一个lambda操作符(->)和一个函数体组成。
返回类型
- 当有一条语句时,匿名函数的返回类型与主体表达式的返回类型相同。
- 当有一个以上的语句用大括号括起来时,匿名函数的返回类型与代码块中返回的值的类型相同,如果没有返回,则为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形成一个闭包。
上一篇: javascript 中的匿名类 js 中的匿名函数角色
下一篇: JS 匿名和命名函数
推荐阅读
-
Java Notes] 第 5 章:函数 - 6.第 5 章:函数 - 6.函数的递归调用
-
在 Java 中,新建对象的内存区域是如何变化的?顺序是什么?
-
Java Series | 特派团中的远程热部署
-
深入分析 Java 中的 MyBatis Plus 注释 @InterceptorIgnore:拦截器行为的优雅控制
-
在 keil (mdk) 中,在编译时删除未使用的函数,以减少代码量。
-
Java中的 JDK8、JDK11、JDK17 该如何选择?
-
35 岁实现财务*,腾讯程序员手握2300万提前退休?-1000万房产、1000万腾讯股票、加上300万的现金,一共2300万的财产。有网友算了一笔账,假设1000万的房产用于自住,剩下1300万资产按照平均税后20-50万不等进行计算,大约花上26-60年左右的时间才能赚到这笔钱。也就是说,普通人可能奋斗一辈子,才能赚到这笔钱。在很多人还在为中年危机而惶惶不可终日的时候,有的人的35岁,就已经安全着陆,试问哪个打工人不羡慕?但问题是有这样财富积累必然有像样的实力做靠山。没有人可以不劳而获。 看到这里,肯定有人说,那么对于普通人来说,卷可能真就成了唯一的出路。但是卷也有轻松的卷,“偷懒”的卷法,对于程序员而言,刨除掉一时无法改掉的开会传统占用的大部分时间,如何把有限的时间和精力放在真正重要的架构设计、需求设计上,而不是重复的造*,编码、改bug、手动测试。因此在科技改变生活的今天,学会使用AI工具成为程序员们的必备技能。 以全栈式全自动的软件开发工具飞算SoFlu软件机器人为例,作为全球首款面向微服务架构设计和最佳实践的软件机器人,SoFlu软件机器人改变了原来手工编码的作业模式,通过可视化拖拽方式以及参数配置就能实现等同于编写复杂代码的业务逻辑,在设计业务逻辑时就完成了微服务应用开发,做到“业务即图,图即代码”,实现“软件开发,十倍提效”。 而作为飞算SoFlu软件机器人的一个重要组成部分,FuncGPT(慧函数)支持所有类型函数创建。通过自然语言描述Java函数需求,实时生成高质量、高可读性的Java函数代码。生成代码可直接复制到IDEA,或一键导入Java全自动开发工具函数库。 FuncGPT(慧函数)具有五大核心能力: ● 自然语言:通过自然语言即可生成函数,降低软件开发门槛。 ● 秒级函数开发:全自动秒级开发函数,秒级完成,效率千倍提升。 ● 一站式函数开发应用:函数生成即可直接应用,效率、安全有保障。 ● 质量可靠:生成的函数代码符合业界规范、具备良好的可读性,符合最优解。 ● 灵活生成:可以根据开发人员的具体需求生成并支持调整和修改。 以“将文件流转换为File对象”这个需求为例,以下是FuncGPT(慧函数)秒级生成的代码: / 类名:FileConverter // 函数名:convertStreamToFile // 函数功能:将文件流转换为File对象 // POM依赖包:无 import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class FileConverter { /** * 将文件流转换为File对象 * @param inputStream 文件流 * @param filePath 文件路径 * @param fileName 文件名 * @return 转换后的File对象 * @throws IOException 如果发生I/O异常 */ public static File convertStreamToFile(InputStream inputStream, String filePath, String fileName) throws IOException { File file = new File(filePath + File.separator + fileName); // 创建File对象 try (FileOutputStream outputStream = new FileOutputStream(file)) { // 创建文件输出流 byte buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { // 从文件流读取数据并写入文件 outputStream.write(buffer, 0, bytesRead); } } return file; // 返回转换后的File对象 } } // 函数示例 // 将文件流转换为File对象示例 // 入参:inputStream,文件流 // 入参:filePath,文件路径 // 入参:fileName,文件名 // 出参:file,转换后的File对象 // 调用示例: // InputStream inputStream = new FileInputStream("example.txt"); // String filePath = "C:\\Users\\User\\Documents"; // String fileName = "example.txt"; // File file = FileConverter.convertStreamToFile(inputStream, filePath, fileName); // System.out.println(file.getAbsolutePath); // 输出结果:例如,将文件流转换为File对象后,文件的绝对路径为:C:\Users\User\Documents\example.txt // 则输出结果为:C:\Users\User\Documents\example.txt 通过分析,不难发现以上代码:
-
Oracle date contemporaneous、Oracle BIEE 中的时间维度和时间轴函数、同期、同比、环比、累计、同期累计计算 | XueBuYuan ...
-
Java 面试问题:解释 Java 中的并发工具类 ConcurrentHashMap 如何工作,并列举经典应用示例
-
贪婪算法在 Python、JavaScript、Java、C++ 和 C# 中的多种实现及其在硬币变化、分数骑士、活动选择和使用哈夫曼编码的最小生成树问题中的应用实例