简体   繁体   English

用方法引用替换lambda表达式

[英]Replacing lambda expression with method reference

I have a static method which takes the parameter Stream<Double> stream . 我有一个静态方法,它接受参数Stream<Double> stream Coming from either a arraylist.stream() or Arrays.stream(array) . 来自arraylist.stream()Arrays.stream(array)

The method's job is to return the sum of all integers that are divisible by three. 该方法的工作是返回可被三整除的所有整数的总和。

return stream.filter(i -> i.intValue() % 3 == 0).mapToInt(i -> i.intValue()).sum()

This method works, however IntelliJ is suggesting the following: 此方法有效,但IntelliJ建议如下:

This inspection reports lambdas which can be replaced with method references. 此检查报告lambda,可以用方法引用替换。

I'm not overly familiar with method references, especially the referencing instance methods using class names scenario. 我不太熟悉方法引用,尤其是使用类名方案的引用实例方法。

I have tried the following which gives an error. 我尝试了下面的错误。

stream.filter(i -> i.intValue() % 3 == 0).mapToInt(Integer::intValue).sum()

Any suggestions? 有什么建议?

As you said the parameter stream is type of Double, so you should do 正如你所说的参数流是Double的类型,所以你应该这样做

stream.mapToInt(Double::intValue).filter(i -> i % 3 == 0).sum()

because you are calling Double class' intValue function. 因为你正在调用Double类的intValue函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM