How to apply a Stream reduction (count) to a IntStream and change the return type to “int”

  • A+
Category:Languages

This code won't compile:

public int trailingZeroes(int n) {     return IntStream.rangeClosed(1,n)             .filter(e -> (e  % 5) == 0)             .count(); } 

I noticed this difference in the return types of IntStream methods:

int sum() vs long count()

While trying to return an int type from the counting operation above,

  • I already understand why count() returns a long but why have sum() return a narrower return type than count()?

  • What would be the best way to achieve what I'm trying to do in my
    trailingZeroes method?

 


I already understand why count() returns a long but why have sum() return a narrower return type than count()?

sum() returns the sum of the items in the stream, so the type returned matches the type of the stream. LongStream.sum() returns long.

The count() is not directly related to the type of the objects coming from the stream, and to conform with the rest of the Stream classes they chose long, the type that represents the largest size. The count() method is actually defined at the Stream interface level, which is then extended by BaseStream, and subsequently by IntStream, so the contract of the method signature has to be preserved. (Ideally count() should have returned unsigned, but Java doesn't support unsigned.)

What would be the best way to achieve what I'm trying to do in my trailingZeroes method?

Not clear what you are trying to achieve. But I see nothing particularly wrong with it.

If you want it to return int, cast the value before returning. I presume you know that the result will always fit safely in an int (the result will always be less than n which is an int), unless you want to change the return type of your method to long.

On the other hand can't understand what this method is supposed to be doing. You could have just done:

public int trailingZeroes(int n) {   return n / 5; } 

If you are looking for a mathematical way to determine how many trailing 0s you have in an integer, it would be different. You already have a suggested answer, so taking the liberty to suggest a recursive solution for the fun of it:

public int trailingZeroes(int n) {    return (n % 10 != 0)          ? 0          : 1 + trailingZeroes(n / 10); } 

Comment

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