Liam Ferris
Liam Ferris

Reputation: 1846

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?

Upvotes: 6

Views: 9482

Answers (1)

Utkan Ozyurek
Utkan Ozyurek

Reputation: 638

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.

Upvotes: 7

Related Questions