Lambda表达式在流畅的API中的应用?

huangapple go评论71阅读模式
英文:

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-&gt;t&gt;4).count();

Anonymous class

                list.stream()//line1
                .map(String::length)
                .filter(new Predicate&lt;Integer&gt;() {
					@Override
					public boolean test(Integer t) {//line 5
						
						return t&gt;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 -&gt; t &gt; 4, Java automatically infers the type of this lambda -- it must be a Predicate&lt;Integer&gt;, given that it's being passed to filter on a Stream&lt;Integer&gt; -- and then automatically figures out that it must be (Integer t) -&gt; t &gt; 4.

huangapple
  • 本文由 发表于 2020年10月24日 02:33:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64505583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定