00:00

Java IntStream Examples

Last updated:

IntStream is the primitive specialisation of Stream for int values, defined in java.util.stream since Java 8. It is the stream you reach for when working with counters, indexes, character codes, scores and other whole numbers that fit in 32 bits.

The IntStream, LongStream, DoubleStream tutorial explains how to create primitive streams. This page is a collection of practical IntStream tasks: index loops, number checks, nested loops, character analysis and statistics, each as a complete program verified on Java 25.

1. Key IntStream Methods

IntStream.java (API)
// Frequently used java.util.stream.IntStream methods (Java 8 unless noted)
static IntStream range(int startInclusive, int endExclusive)
static IntStream rangeClosed(int startInclusive, int endInclusive)
static IntStream iterate(int seed, IntPredicate hasNext, IntUnaryOperator next)   // Java 9
IntStream filter(IntPredicate p)          IntStream map(IntUnaryOperator f)
<U> Stream<U> mapToObj(IntFunction<U> f)   IntStream flatMap(IntFunction<IntStream> f)
int sum()   OptionalInt max()   OptionalDouble average()   long count()
IntSummaryStatistics summaryStatistics()   Stream<Integer> boxed()   int[] toArray()

Its functional interfaces are the int versions of the usual ones: IntPredicate, IntUnaryOperator, IntFunction, IntBinaryOperator and IntConsumer.

2. How IntStream Works

An IntStream behaves like any other stream: it is lazy, single-use and can be parallel. The difference is that its elements are int values held directly, and its terminal operations return numeric results such as int, OptionalInt and OptionalDouble.

You move between worlds with three methods: mapToObj() or boxed() to get objects, and mapToInt() on a Stream to get back to an IntStream.

A typical IntStream pipeline IntStream.rangeClosed 1 to 50 produces the numbers 1 to 50. filter keeps the multiples of 7. map squares each one. sum adds the squares into a single int. No value is boxed at any step. rangeClosed1 .. 50 SOURCE filtern % 7 == 0 mapn * n sum()int result TERMINAL INT STAGES
Figure 1: Every stage works on plain int values, so no Integer objects are created.

3. IntStream Examples

Example 1: Index-based processing of a list (Java 9+)

Print a numbered list of tasks, and find the positions of the urgent ones.

IndexedTasks.java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class IndexedTasks {

    public static void main(String[] args) {
        List<String> tasks = List.of("pay rent", "URGENT renew passport", "buy milk", "URGENT file taxes");

        IntStream.range(0, tasks.size())
                .mapToObj(i -> (i + 1) + ". " + tasks.get(i))
                .forEach(System.out::println);

        List<Integer> urgentPositions = IntStream.range(0, tasks.size())
                .filter(i -> tasks.get(i).startsWith("URGENT"))
                .boxed()
                .collect(Collectors.toList());
        System.out.println("Urgent at indexes: " + urgentPositions);
    }
}
Output
1. pay rent
2. URGENT renew passport
3. buy milk
4. URGENT file taxes
Urgent at indexes: [1, 3]

How it works: Streaming the indexes gives you both the position and the element, which a plain element stream does not. boxed() is needed to collect the indexes into a List<Integer>.

Example 2: Prime numbers in a range

List the prime numbers between 1 and 50 and count them.

PrimesUpTo50.java
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class PrimesUpTo50 {

    static boolean isPrime(int n) {
        return n > 1 && IntStream.rangeClosed(2, (int) Math.sqrt(n)).noneMatch(d -> n % d == 0);
    }

    public static void main(String[] args) {
        String primes = IntStream.rangeClosed(1, 50)
                .filter(PrimesUpTo50::isPrime)
                .mapToObj(String::valueOf)
                .collect(Collectors.joining(" "));

        long count = IntStream.rangeClosed(1, 50).filter(PrimesUpTo50::isPrime).count();

        System.out.println(primes);
        System.out.println(count + " primes");
    }
}
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
15 primes

How it works: isPrime() itself uses an IntStream of possible divisors up to the square root, and noneMatch() stops at the first divisor found.

Example 3: Nested loops with flatMap (Java 9+)

Generate all seat labels for rows A to C and seats 1 to 3 in a small auditorium.

SeatGrid.java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SeatGrid {

    public static void main(String[] args) {
        List<String> seats = IntStream.rangeClosed('A', 'C')
                .boxed()
                .flatMap(row -> IntStream.rangeClosed(1, 3).mapToObj(seat -> (char) row.intValue() + "" + seat))
                .collect(Collectors.toList());

        System.out.println(seats);
        System.out.println("Total seats: " + seats.size());
    }
}
Output
[A1, A2, A3, B1, B2, B3, C1, C2, C3]
Total seats: 9

How it works: Characters are int codes, so rangeClosed('A', 'C') streams the rows. flatMap() replaces two nested for loops; each row expands into its three seats.

Example 4: Character analysis of a password

Check a password for digits, upper-case letters and special characters.

PasswordStrength.java
public class PasswordStrength {

    public static void main(String[] args) {
        String password = "Mumbai@2026";

        long digits = password.chars().filter(Character::isDigit).count();
        long upper = password.chars().filter(Character::isUpperCase).count();
        long special = password.chars().filter(c -> !Character.isLetterOrDigit(c)).count();
        boolean strong = password.length() >= 8 && digits > 0 && upper > 0 && special > 0;

        System.out.println("digits=" + digits + ", upper=" + upper + ", special=" + special);
        System.out.println("Strong password? " + strong);
    }
}
Output
digits=4, upper=1, special=1
Strong password? true

How it works: String.chars() returns an IntStream of character codes, and the Character class methods that accept an int work directly as predicates.

Example 5: Digit sum and statistics

Compute the digit sum of a number and summarise a set of exam scores.

DigitsAndStats.java
import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;

public class DigitsAndStats {

    public static void main(String[] args) {
        int accountNumber = 40213987;
        int digitSum = String.valueOf(accountNumber).chars().map(c -> c - '0').sum();
        System.out.println("Digit sum: " + digitSum);

        IntSummaryStatistics scores = IntStream.of(67, 82, 91, 45, 73, 88).summaryStatistics();
        System.out.printf("Scores: min %d, max %d, average %.2f%n",
                scores.getMin(), scores.getMax(), scores.getAverage());
    }
}
Output
Digit sum: 34
Scores: min 45, max 91, average 74.33

How it works: Subtracting '0' turns a digit's character code into its numeric value. summaryStatistics() gives several statistics in one pass.

4. Real-World Use Cases

  • Index loops over lists and arrays when the position matters.
  • Number utilities: primes, divisors, digit operations, check digits.
  • Grids and combinations: seats, calendar cells, coordinate pairs with flatMap().
  • Text checks: password rules, character counts, simple parsing.

5. Important Points

  • Overflow: sum() returns int and can overflow; use asLongStream() for large totals.
  • Empty streams: max() and average() return empty optionals.
  • Characters: chars() gives UTF-16 code units; use codePoints() for emoji and other supplementary characters.
  • Collecting: call boxed() before collect(Collectors.toList()) or toList().
  • Ranges: range() excludes the end; see range() vs rangeClosed().

6. IntStream vs Classic Loops

TaskIntStream approachClassic approach
Loop 0 to n-1IntStream.range(0, n)for (int i = 0; i < n; i++)
Sum of valuesIntStream.of(...).sum()Accumulator variable
Nested loopsflatMap() or mapToObj()Two for loops
Early exitanyMatch(), takeWhile()break
Mutating an array in placeAwkwardNatural with a loop

Streams express searches and summaries well; loops remain clearer for in-place array updates.

7. Common Mistakes and Best Practices

Collecting without boxing

Wrong
List<Integer> evens = IntStream.range(0, 10).filter(n -> n % 2 == 0).collect(Collectors.toList());   // does not compile

Add .boxed() before collecting, or use toArray() for an int[].

Overflowing sum()

SumOfSquares.java
import java.util.stream.IntStream;

public class SumOfSquares {

    public static void main(String[] args) {
        int wrong = IntStream.rangeClosed(1, 2000).map(n -> n * n).sum();
        long right = IntStream.rangeClosed(1, 2000).asLongStream().map(n -> n * n).sum();

        System.out.println("int:  " + wrong);
        System.out.println("long: " + right);
    }
}
Output
int:  -1626300296
long: 2668667000

Other mistakes to avoid

  • Using Stream<Integer> for arithmetic. Map to an IntStream first.
  • Using index streams where an element stream works. list.stream() is clearer when the index is not needed.
  • Calling getAsInt() on a possibly empty result.

8. Summary

  • IntStream works on plain int values and adds numeric operations.
  • Stream indexes with range() when the position matters.
  • Use flatMap() for nested loops and chars() for text.
  • Box before collecting, and switch to long for large sums.

9. References