问题描述
lambda表达式是在我们编写它们的地方还是在任何其他Java类中求值的?
Are the lambda expressions evaluated at the place where we write them or in any other class of Java?
例如:
Stream<Student> absent = students.values().stream().filter(s -> !s.present());
将将上面传递给filter方法的lambda表达式在编写代码的给定类中立即执行,或者在另一个类中执行,将比在编写代码时花费更多的时间(以纳秒为单位) Java 8之前的传统编码风格?
Will the above lambda expression passed to the filter method be executed immediately in a given class where the code is written OR in another class and will it take some more time (in terms of nano seconds) than if the code was written in conventional coding style prior to Java 8?
推荐答案
编译源代码时,编译器将为您使用的lambda表达式插入invokedynamic
字节代码指令.实际的实现(在您的情况下为Predicate
)将在运行时通过ASM
创建 .当您运行它时,它甚至不会出现在硬盘上-意味着该类在内存中生成,Predicate
没有任何.class
文件.例如,这与匿名类之间有很大的不同-编译 时,它将生成一个class
文件.
When you compile your sources, the compiler will insert an invokedynamic
byte code instruction for the lambda expression that you use. The actual implementation (which in your case is a Predicate
) will be created at runtime via ASM
. It will not even be present on hard disk when you run it - meaning the class is generated in memory, there will be no .class
file for Predicate
. That's a big difference between an anonymous class for example - that will generate a class
file when you compile it.
如果使用:p来运行示例,则可以看到Predicate
的生成文件.
You can see the generated file for the Predicate
if you run your example with :
-Djdk.internal.lambda.dumpProxyClasses=/Your/Path/Here
否则 Eran的答案是正确的,Stream
是由终端操作驱动的,如果不存在则什么也没有被执行.您应该绝对阅读出色的有关更有趣的差异.
Otherwise Eran's answer is correct, Stream
s are driven by the terminal operation, if such is not present nothing gets executed. You should absolutely read the excellent Holger's answer about even more interesting differences.
这篇关于Java 8 Lambda表达式在哪里求值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!