Skip to lesson

Number ranges with IntStream.range

IntStream.range(start, end) makes a stream of whole numbers from start up to, but not including, end. It is the stream version of a counting for loop, and rangeClosed(start, end) is the same with end included.

range versus rangeClosed

A counting loop for (int i = 1; i < 6; i++) visits 1, 2, 3, 4, 5. IntStream.range(1, 6) gives exactly the same numbers. The end is exclusive: it is the first number that is not included, just like i < 6.

On the numbers 1 to 6, IntStream.range(1, 5) covers 1, 2, 3 and 4 and leaves 5 out. IntStream.rangeClosed(1, 5) covers 1, 2, 3, 4 and 5 and includes the end.

Example 1 · range and rangeClosed side by side

RangeDemo.javaJava
import java.util.stream.IntStream;
public class RangeDemo {    public static void main(String[] args) {        System.out.println("range(1, 6):       " + IntStream.range(1, 6).boxed().toList());        System.out.println("rangeClosed(1, 5): " + IntStream.rangeClosed(1, 5).boxed().toList());        System.out.println("range(0, 4):       " + IntStream.range(0, 4).boxed().toList());        System.out.println("range(5, 5):       " + IntStream.range(5, 5).boxed().toList());        System.out.println("Count of range(10, 20): " + IntStream.range(10, 20).count());    }}
Output
range(1, 6):       [1, 2, 3, 4, 5]
rangeClosed(1, 5): [1, 2, 3, 4, 5]
range(0, 4):       [0, 1, 2, 3]
range(5, 5):       []
Count of range(10, 20): 10

What this code does

  • range(1, 6) stops before 6, while rangeClosed(1, 5) includes 5, so both give 1 to 5. range(0, 4) gives the four indexes of a 4-element list.
  • An empty range such as range(5, 5) is not an error; it just has no numbers. range(a, b) always has b - a numbers, here 10.

IntStream.rangeClosed(1, 5) gives 1 to 5 too, but here the end is inclusive, like i <= 5. Use rangeClosed when the task names both ends, such as "roll numbers 1 to 60". Use range for indexes, where the end is a size such as list.size(). If the start is not smaller than the end, the stream is simply empty: range(5, 5) and range(9, 2) give no numbers and no error. range(a, b) has b - a numbers. LongStream.range and LongStream.rangeClosed work the same way for long values.

Predict the output

Predict the range

Does the end value count? Work out what each program prints.

Round 1 of 3

What does this print?

import java.util.stream.IntStream;
public class RangeSum {
public static void main(String[] args) {
System.out.println(IntStream.range(1, 5).sum());
}
}
A range only counts up by 1. For steps of 2 or counting down, use iterate from the next lesson, or map(i -> i * 2) on a range.

Replacing simple counting loops

Many loops exist only to count: add 1 to 100, print a multiplication table, multiply 1 to n for a factorial. A range plus one stream operation says the same thing in one line, and there is no loop variable to get wrong.

Example 2 · Counting loops as one-line streams

CountingLoopsDemo.javaJava
import java.util.stream.IntStream;import java.util.stream.LongStream;
public class CountingLoopsDemo {    public static void main(String[] args) {        // loop version of 1 + 2 + ... + 100        int loopSum = 0;        for (int i = 1; i <= 100; i++) {            loopSum += i;        }        System.out.println("Loop sum:   " + loopSum);        System.out.println("Stream sum: " + IntStream.rangeClosed(1, 100).sum());
        System.out.println("Multiples of 7 up to 100: "                + IntStream.rangeClosed(1, 100).filter(i -> i % 7 == 0).count());
        IntStream.rangeClosed(1, 5)                .mapToObj(i -> "7 x " + i + " = " + 7 * i)                .forEach(System.out::println);
        long factorial15 = LongStream.rangeClosed(1, 15).reduce(1, (a, b) -> a * b);        System.out.println("15! = " + factorial15);    }}
Output
Loop sum:   5050
Stream sum: 5050
Multiples of 7 up to 100: 14
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
15! = 1307674368000

What this code does

  • Each counting loop becomes a range plus one operation: sum(), filter with count(), or mapToObj to build lines of text.
  • 15 factorial is 1307674368000, far beyond the int limit, so the factorial uses LongStream.rangeClosed and reduce with identity 1 in long.
  • Why range: a range has no loop variable to start, test or step wrongly, and the intent (the numbers 1 to 10) is visible in one call.

Keep the loop when it does more than count. A loop that must stop early with break, update two or three variables at once, or print and change state in the same step is often clearer as a plain for loop. The stream is a better choice when the task is "these numbers, filtered or changed, then combined".

  • Sum 1 to n: IntStream.rangeClosed(1, n).sum().
  • Table of 7: IntStream.rangeClosed(1, 10).mapToObj(i -> "7 x " + i + " = " + 7 * i).
  • Factorial: LongStream.rangeClosed(1, n).reduce(1, (a, b) -> a * b), in long because it grows fast.
  • Count matches: IntStream.rangeClosed(1, 100).filter(i -> i % 7 == 0).count().

Using indexes with range over a list or array

A stream over a list gives the elements but not their positions. When you need the position, stream the indexes instead: IntStream.range(0, list.size()). Inside the lambda, list.get(i) or array[i] reads the element.

Example 3 · Indexes: ranks and day-to-day drops

RankAndDropDemo.javaJava
import java.util.List;import java.util.stream.IntStream;
public class RankAndDropDemo {    public static void main(String[] args) {        List<String> toppers = List.of("Priya", "Kavya", "Aarav");        List<Integer> marks = List.of(96, 91, 88);
        IntStream.range(0, toppers.size())                .mapToObj(i -> (i + 1) + ". " + toppers.get(i) + " - " + marks.get(i))                .forEach(System.out::println);
        int[] present = {52, 55, 49, 58, 50, 50};        String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
        List<String> drops = IntStream.range(1, present.length)                .filter(i -> present[i] < present[i - 1])                .mapToObj(i -> days[i] + " (" + present[i - 1] + " -> " + present[i] + ")")                .toList();        System.out.println("Attendance dropped on: " + drops);    }}
Output
1. Priya - 96
2. Kavya - 91
3. Aarav - 88
Attendance dropped on: [Wed (55 -> 49), Fri (58 -> 50)]

What this code does

  • Streaming the indexes 0, 1, 2 gives each topper and the matching mark from a second list, plus a rank i + 1. A plain toppers.stream() cannot see positions.
  • For neighbours the range starts at 1, so present[i - 1] is always valid. Saturday equals Friday, so it is not a drop.

Example 4 · Mistake: rangeClosed over indexes

IndexTrapDemo.javaJava
import java.util.List;import java.util.stream.IntStream;
public class IndexTrapDemo {    public static void main(String[] args) {        List<String> seats = List.of("A1", "A2", "A3");
        try {            List<String> labels = IntStream.rangeClosed(0, seats.size())                    .mapToObj(i -> "Seat " + seats.get(i))                    .toList();            System.out.println(labels);        } catch (IndexOutOfBoundsException e) {            System.out.println("Crash: " + e.getMessage());        }
        List<String> fixed = IntStream.range(0, seats.size())                .mapToObj(i -> "Seat " + seats.get(i))                .toList();        System.out.println("Fixed: " + fixed);    }}
Output
Crash: Index 3 out of bounds for length 3
Fixed: [Seat A1, Seat A2, Seat A3]

What this code does

  • rangeClosed(0, 3) includes 3, but a 3-element list has only indexes 0, 1 and 2, so seats.get(3) throws.
  • range(0, seats.size()) stops before the size, exactly like i < seats.size() in a loop. For indexes, always use range.

This helps in three common cases: printing a rank such as "1. Aarav", reading two lists that line up (names and marks), and comparing an element with its neighbour. For neighbours, start at 1, so that i - 1 is always a valid index. The usual trap is the end. rangeClosed(0, list.size()) includes list.size(), which is one past the last index, and the program throws IndexOutOfBoundsException. For indexes, always use range(0, size).

Characters of a String with chars()

"Pune".chars() returns an IntStream, not a stream of char. Each element is the character code: 80 for P, 117 for u, and so on. Java has no CharStream, so characters travel as int values.

Example 5 · chars(): numbers, not letters

CharsDemo.javaJava
import java.util.List;
public class CharsDemo {    public static void main(String[] args) {        String city = "Pune";        System.out.println("Raw chars(): " + city.chars().boxed().toList());
        List<Character> letters = city.chars().mapToObj(c -> (char) c).toList();        System.out.println("As letters:  " + letters);
        String name = "Aishwarya";        long vowels = name.toLowerCase().chars().filter(c -> "aeiou".indexOf(c) >= 0).count();        System.out.println("Vowels in " + name + ": " + vowels);
        String phone = "98450x2211";        boolean allDigits = phone.chars().allMatch(Character::isDigit);        System.out.println(phone + " is a valid number? " + (allDigits && phone.length() == 10));    }}
Output
Raw chars(): [80, 117, 110, 101]
As letters:  [P, u, n, e]
Vowels in Aishwarya: 4
98450x2211 is a valid number? false

What this code does

  • chars() gives an IntStream of character codes, so boxing it shows numbers such as 80 for P. mapToObj(c -> (char) c) turns each code back into a Character.
  • "aeiou".indexOf(c) and Character.isDigit(c) both accept the int code directly. The x in the phone number makes allMatch return false.

That is why printing them shows numbers. Turn a code back into a character with a cast, (char) c, usually inside mapToObj(c -> (char) c) or mapToObj(c -> String.valueOf((char) c)). Methods such as Character.isDigit(c) and Character.isUpperCase(c) accept the int directly. Real uses: check that a phone number has only digits, count vowels in a name, or count capital letters in a password.

Next step

Check your understanding

11 quick questions