Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing lambda expression with method reference

I have a static method which takes the parameter Stream<Double> stream. Coming from either a arraylist.stream() or 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:

This inspection reports lambdas which can be replaced with method references.

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?

like image 487
Liam Ferris Avatar asked Oct 07 '16 11:10

Liam Ferris


1 Answers

As you said the parameter stream is type of Double, so you should do

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

because you are calling Double class' intValue function.

like image 190
Utkan Ozyurek Avatar answered Sep 18 '22 16:09

Utkan Ozyurek