6

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?

4
  • 6
    Since i is a Double, you should use Double::intValue. IntelliJ not only inspects, but also proposes the change. Just hit alt-enter. Commented Oct 7, 2016 at 11:24
  • 2
    If IntelliJ suggest such a replacement, you can direct it to do that replacement. By the way, it would be more efficient to unbox only once, i.e. .mapToInt(Double::intValue).filter(i -> i % 3 == 0) Commented Oct 7, 2016 at 11:24
  • 1
    @Holger does reversing the order not run the possibility of rounding doubles to ints, which are then divisible by three and change the result? Commented Oct 7, 2016 at 12:08
  • 2
    Your original code, i.intValue() % 3 == 0, already does exactly that. Commented Oct 7, 2016 at 12:28

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.