When should I use IntStream.range in Java?

前端 未结 7 1948
盖世英雄少女心
盖世英雄少女心 2020-12-29 01:34

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

7条回答
  •  有刺的猬
    2020-12-29 02:09

    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:

    • We need to pass them around between methods
    • The target method doesn't just work on ranges but any stream of numbers
    • But it only operates on individual numbers of the stream, reading them sequentially. (This is why shuffling with streams is a terrible idea in general.)

    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 IntStreans 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

提交回复
热议问题