英文:
Lambda of Fluent API?
问题
尝试在Stream API中使用匿名类(以下代码)替换lambda,并且它能正常工作。我想要理解如何从哪里生成test(T t)方法所需的参数。
Lambda
list.stream()
.map(String::length)
.filter(t -> t > 4).count();
匿名类
list.stream()//line1
.map(String::length)
.filter(new Predicate<Integer>() {
@Override
public boolean test(Integer t) {//line 5
return t > 4;
}
}).count();
在使用lambda时,我们使用lambda表示法传递参数,但我不明白第5行的Integer t
是如何生成的。是由于Stream
中的Fluent API
还是由于函数式接口(lambda)?
编辑:我清楚关于lambda
版本,不明白带有anonymous class
的版本是如何工作的?换句话说,在Java 1.7
中是否会工作(假设我们编写了与Stream API
类似的东西,只是没有lambda)。
编辑:对于像我一样困惑的人,请查看https://github.com/fmcarvalho/quiny,这是一位聪明人简化的Stream API实现。
英文:
Tried to replace lambdas with anonymous class in Stream API (below code) and it works fine. I want to understand how the parameter required for the test(T t) method is getting generated from.
Lambda
list.stream()
.map(String::length)
.filter(t->t>4).count();
Anonymous class
list.stream()//line1
.map(String::length)
.filter(new Predicate<Integer>() {
@Override
public boolean test(Integer t) {//line 5
return t>4;
}
}).count();
While using lambdas we pass the parameter using the lambda notation, but I dont understand how the Integer t
at line 5 is getting generated from. Is it due to the Fluent API
in Stream
or due to the functional interface(lambda)?
Edit : I am clear about lambda
version, dont understand how the version with anonymous class
is working? To put in another way, would it work in Java 1.7
(provided we wrote something similar to Stream API
, we just wont have lambdas).
Edit : For anyone confused like I was, please look at https://github.com/fmcarvalho/quiny , simplified implementation of Stream API by some smart guy
答案1
得分: 1
当你写下 t -> t > 4
,Java 会自动推断出这个lambda的类型 -- 它必须是一个 Predicate<Integer>
,因为它被传递给了一个 Stream<Integer>
上的 filter
方法 -- 然后自动推导出它必须是 (Integer t) -> t > 4
。
英文:
When you write t -> t > 4
, Java automatically infers the type of this lambda -- it must be a Predicate<Integer>
, given that it's being passed to filter
on a Stream<Integer>
-- and then automatically figures out that it must be (Integer t) -> t > 4
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论