Java IntStream Examples
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
// 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.
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.
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);
}
}
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.
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");
}
}
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.
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());
}
}
[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.
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);
}
}
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.
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());
}
}
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()returnsintand can overflow; useasLongStream()for large totals. - Empty streams:
max()andaverage()return empty optionals. - Characters:
chars()gives UTF-16 code units; usecodePoints()for emoji and other supplementary characters. - Collecting: call
boxed()beforecollect(Collectors.toList())ortoList(). - Ranges:
range()excludes the end; see range() vs rangeClosed().
6. IntStream vs Classic Loops
| Task | IntStream approach | Classic approach |
|---|---|---|
| Loop 0 to n-1 | IntStream.range(0, n) | for (int i = 0; i < n; i++) |
| Sum of values | IntStream.of(...).sum() | Accumulator variable |
| Nested loops | flatMap() or mapToObj() | Two for loops |
| Early exit | anyMatch(), takeWhile() | break |
| Mutating an array in place | Awkward | Natural 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
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()
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);
}
}
int: -1626300296 long: 2668667000
Other mistakes to avoid
- Using
Stream<Integer>for arithmetic. Map to anIntStreamfirst. - 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
IntStreamworks on plainintvalues and adds numeric operations.- Stream indexes with
range()when the position matters. - Use
flatMap()for nested loops andchars()for text. - Box before collecting, and switch to
longfor large sums.
9. References
Frequently Asked Questions (FAQ)
Q1. What is IntStream in Java?
IntStream is the primitive specialisation of Stream for int values, added in Java 8. It avoids boxing and provides numeric operations such as sum(), average(), max(), range() and summaryStatistics().
Q2. How do I loop with an index using IntStream?
Use IntStream.range(0, list.size()) and access list.get(i) inside the pipeline, for example to print numbered items or find positions of matches.
Q3. How do I convert an IntStream to a List?
Call boxed() to get a Stream<Integer>, then toList() or collect(Collectors.toList()).
Q4. How do I avoid overflow when summing an IntStream?
Convert to a LongStream with asLongStream() before summing, or use summaryStatistics().getSum(), which returns a long.
Q5. How do I iterate over the characters of a String with IntStream?
Use text.chars() for UTF-16 code units or text.codePoints() for full Unicode code points. Both return an IntStream of character codes.