I would like to know when I can use IntStream.range
effectively. I have three reasons why I am not sure how useful IntStream.range
is.
(Ple
Here's an example:
public class Test {
public static void main(String[] args) {
System.out.println(sum(LongStream.of(40,2))); // call A
System.out.println(sum(LongStream.range(1,100_000_000))); //call B
}
public static long sum(LongStream in) {
return in.sum();
}
}
So, let's look at what sum()
does: it counts the sum of an arbitrary stream of numbers. We call it in two different ways: once with an explicit list of numbers, and once with a range.
If you only had call A
, you might be tempted to put the two numbers into an array and pass it to sum()
but that's clearly not an option with call B
(you'd run out of memory). Likewise you could just pass the start and end for call B
, but then you couldn't support the case of call A
.
So to sum it up, ranges are useful here because:
There is also the readability argument: code using streams can be much more concise than loops, and thus more readable, but I wanted to show an example where a solution relying on IntStrean
s is functionally superior too.
I used LongStream
to emphasise the point, but the same goes for IntStream
And yes, for simple summing this may look like a bit of an overkill, but consider for example reservoir sampling