There are several uses for IntStream.range.

One is to use the int values themselves:

IntStream.range(start, end).filter(i -> isPrime(i))....

Another is to do something N times:

IntStream.range(0, N).forEach(this::doSomething);

Your case (1) is to create an array filled with a range:

int[] arr = IntStream.range(start, end).toArray();

You say this is "very slow" but, like other respondents, I suspect your benchmark methodology. For small arrays there is indeed more overhead with stream setup, but this should be so small as to be unnoticeable. For large arrays the overhead should be negligible, as filling a large array is dominated by memory bandwidth.

Sometimes you need to fill an existing array. You can do that this way:

int[] arr = new int[end - start];
IntStream.range(0, end - start).forEach(i -> arr[i] = i + start);

There's a utility method Arrays.setAll that can do this even more concisely:

int[] arr = new int[end - start];
Arrays.setAll(arr, i -> i + start);

There is also Arrays.parallelSetAll which can fill an existing array in parallel. Internally, it simply uses an IntStream and calls parallel() on it. This should provide a speedup for large array on a multicore system.

I've found that a fair number of my answers on Stack Overflow involve using IntStream.range. You can search for them using these search criteria in the search box:

user:1441122 IntStream.range

One application of IntStream.range I find particularly useful is to operate on elements of an array, where the array indexes as well as the array's values participate in the computation. There's a whole class of problems like this.

For example, suppose you want to find the locations of increasing runs of numbers within an array. The result is an array of indexes into the first array, where each index points to the start of a run.

To compute this, observe that a run starts at a location where the value is less than the previous value. (A run also starts at location 0). Thus:

    int[] arr = { 1, 3, 5, 7, 9, 2, 4, 6, 3, 5, 0 };
    int[] runs = IntStream.range(0, arr.length)
                          .filter(i -> i == 0 || arr[i-1] > arr[i])
                          .toArray();
    System.out.println(Arrays.toString(runs));

    [0, 5, 8, 10]

Of course, you could do this with a for-loop, but I find that using IntStream is preferable in many cases. For example, it's easy to store an unknown number of results into an array using toArray(), whereas with a for-loop you have to handle copying and resizing, which distracts from the core logic of the loop.

Finally, it's much easier to run IntStream.range computations in parallel.

Answer from Stuart Marks on Stack Overflow
Top answer
1 of 8
50

There are several uses for IntStream.range.

One is to use the int values themselves:

IntStream.range(start, end).filter(i -> isPrime(i))....

Another is to do something N times:

IntStream.range(0, N).forEach(this::doSomething);

Your case (1) is to create an array filled with a range:

int[] arr = IntStream.range(start, end).toArray();

You say this is "very slow" but, like other respondents, I suspect your benchmark methodology. For small arrays there is indeed more overhead with stream setup, but this should be so small as to be unnoticeable. For large arrays the overhead should be negligible, as filling a large array is dominated by memory bandwidth.

Sometimes you need to fill an existing array. You can do that this way:

int[] arr = new int[end - start];
IntStream.range(0, end - start).forEach(i -> arr[i] = i + start);

There's a utility method Arrays.setAll that can do this even more concisely:

int[] arr = new int[end - start];
Arrays.setAll(arr, i -> i + start);

There is also Arrays.parallelSetAll which can fill an existing array in parallel. Internally, it simply uses an IntStream and calls parallel() on it. This should provide a speedup for large array on a multicore system.

I've found that a fair number of my answers on Stack Overflow involve using IntStream.range. You can search for them using these search criteria in the search box:

user:1441122 IntStream.range

One application of IntStream.range I find particularly useful is to operate on elements of an array, where the array indexes as well as the array's values participate in the computation. There's a whole class of problems like this.

For example, suppose you want to find the locations of increasing runs of numbers within an array. The result is an array of indexes into the first array, where each index points to the start of a run.

To compute this, observe that a run starts at a location where the value is less than the previous value. (A run also starts at location 0). Thus:

    int[] arr = { 1, 3, 5, 7, 9, 2, 4, 6, 3, 5, 0 };
    int[] runs = IntStream.range(0, arr.length)
                          .filter(i -> i == 0 || arr[i-1] > arr[i])
                          .toArray();
    System.out.println(Arrays.toString(runs));

    [0, 5, 8, 10]

Of course, you could do this with a for-loop, but I find that using IntStream is preferable in many cases. For example, it's easy to store an unknown number of results into an array using toArray(), whereas with a for-loop you have to handle copying and resizing, which distracts from the core logic of the loop.

Finally, it's much easier to run IntStream.range computations in parallel.

2 of 8
7

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

🌐
GeeksforGeeks
geeksforgeeks.org › java › intstream-range-java
IntStream range() in Java - GeeksforGeeks
December 6, 2018 - // Implementation of IntStream ... Output: 6 7 8 9 Note : IntStream range(int startInclusive, int endExclusive) basically works like a for loop....
🌐
Baeldung
baeldung.com › home › java › java streams › understanding the difference between stream.of() and intstream.range()
Understanding the Difference Between Stream.of() and IntStream.range() | Baeldung
March 7, 2025 - On the other hand, IntStream.range() returns a sequentially-ordered IntStream. That’s to say, the input of the IntStream object is already sorted. Furthermore, when it sorts an already sorted input, Java applies the optimization to make the ...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › stream › IntStream.html
IntStream (Java Platform SE 8 )
October 20, 2025 - Returns a Stream consisting of the elements of this stream, each boxed to an Integer.
🌐
Javabrahman
javabrahman.com › java-8 › java-8-how-to-use-range-rangeclosed-methods-of-intstream-longstream-with-examples
Java 8 - How to use range(), rangeClosed() methods of ...
This Java 8 code tip shows, with code examples, when and how to use static methods range() and rangeClosed() available in java.util.stream.IntStream and java.util.stream.LongStream interfaces to create a stream of numbers starting from a specified initial value to an end value.
🌐
TutorialsPoint
tutorialspoint.com › intstream-range-method-in-java
IntStream range() method in Java
This returns a sequential ordered IntStream by an incremental step of 1 within the range − ... import java.util.*; import java.util.stream.IntStream; public class Demo { public static void main(String[] args) { IntStream intStream = IntStream.range(20, 30); intStream.forEach(System.out::println); ...
🌐
Medium
neesri.medium.com › primitive-type-in-stream-java-8-fb587f5c1e5b
Mastering IntStream in Java 8. In Java 8 and later versions, the… | by A cup of JAVA coffee with NeeSri | Medium
July 20, 2025 - IntStream is a specialized stream for handling primitive integers (int). It provides a sequence of primitive int values and supports various operations such as filtering, mapping, reduction, and iteration.
Find elsewhere
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Exploring Java 8 IntStream: Practical Examples and Usage - Java Code Geeks
January 29, 2024 - Firstly, prefer using the range method for generating sequential ranges of integers. Employ method chaining to create concise and readable pipelines of operations. For parallel processing, assess the performance impact and consider factors like statelessness and thread safety. Be cautious when using the boxed() method for converting IntStream to Stream, as it incurs the overhead of boxing primitive values.
🌐
Tabnine
tabnine.com › home page › code › java › java.util.stream.intstream
java.util.stream.IntStream.range java code examples | Tabnine
@Test public void testFetch() { stream.pause(); assertFalse(stream.emit(IntStream.range(0, 17).boxed())); for (int i = 1;i < 17;i++) { stream.fetch(1); assertEquals(IntStream.range(0, i).boxed().collect(Collectors.toList()), emitted); assertEquals(0, drained); } stream.fetch(1); assertEquals(IntStream.range(0, 17).boxed().collect(Collectors.toList()), emitted); assertEquals(1, drained); } ... public void checkPlanIsDeterministic(Session session, String sql) { IntStream.range(1, MINIMUM_SUBSEQUENT_SAME_PLANS) .mapToObj(attempt -> getPlanText(session, sql)) .map(planEquivalenceFunction) .reduce((previous, current) -> { assertEquals(previous, current); return current; }); } ... private List<Integer> rangeList(int endExclusive) { return IntStream.range(0, endExclusive) .boxed() .collect(toImmutableList()); }
🌐
Blogger
javarevisited.blogspot.com › 2021 › 05 › java-8-intstream-examples-range-sum-rangeclosed-max.html
How to use Stream range, rangeClosed, sum and sorted methods? Java 8 IntStream Examples -
* @author Javin */ public class Test { public static void main(String args[]) { // Now let's see some IntStream examples with objects with filter List candidates = new ArrayList&lt;&gt;(); candidates.add(new Student("John", 33)); candidates.add(new Student("Jack", 11)); candidates.add(new Student("Rick", 50)); candidates.add(new Student("Shane", 90)); System.out.println("list of candidates : " + candidates); // Now let's print name of topper int highestMarks = candidates.stream() .mapToInt(s -&gt; s.getMarks()) .max().getAsInt(); System.out.println("highest marks : " + highestMarks); long numO
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › guide to intstream in java
Guide to IntStream in Java - HowToDoInJava
March 4, 2022 - range(int start, int end) – Returns a sequential ordered int stream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1.
🌐
LabEx
labex.io › tutorials › java-how-to-use-the-rangeclosed-method-of-intstream-415163
How to use the rangeClosed() method of IntStream | LabEx
One of the common operations in IntStream is the rangeClosed() method, which allows you to create a stream of consecutive integer values within a specified range, including the endpoints.
🌐
Java Guides
javaguides.net › 2024 › 07 › java-intstream-range-method.html
Java IntStream range() Method
July 3, 2024 - The IntStream.range() method is used to create a sequential ordered IntStream from a start value (inclusive) to an end value (exclusive). This method is particularly useful for generating streams of consecutive integers.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java 8 IntStream With Working Examples - Java Code Geeks
January 3, 2022 - IntStream of(int… values) – Returns a stream with all the components supplied. range() is used to generate the numbers in the order with incremental by one.
🌐
Javadevcentral
javadevcentral.com › a dive deep on java 8 intstream
A dive deep on Java 8 IntStream | Java Developer Central
May 14, 2019 - It then returns an ordered IntStream backed up by those elements. IntStream.of(1, 2, 3) .forEach(System.out::println); Using the range method, we can create an ordered Intstream from a range of numbers.
🌐
LabEx
labex.io › tutorials › java-how-to-use-intstream-in-java-streams-467224
How to use IntStream in Java streams | LabEx
It is part of the Java Stream API introduced in Java 8, providing an efficient and functional way to process integer sequences. // Generate IntStream using various methods IntStream numbers1 = IntStream.of(1, 2, 3, 4, 5); IntStream numbers2 ...