Primitive Streams in Java
Primitive streams in Java are streams of numbers that hold plain int, long or double values instead of Integer, Long or Double objects. There are three classes: IntStream, LongStream and DoubleStream. They are used for number crunching, because they avoid boxing and add handy math methods such as sum(), average(), max() and summaryStatistics(). In this lesson, you will learn how to create primitive streams, convert to and from them, and use their methods.
Creating Primitive Streams
| Method | Description |
|---|---|
IntStream.range(a, b) | It creates the numbers from a to b - 1. |
IntStream.rangeClosed(a, b) | It creates the numbers from a to b. |
IntStream.of(1, 2, 3) | It creates a stream of the given values. |
Arrays.stream(intArray) | It streams an int[]. |
stream.mapToInt(f) | It converts a Stream<T> into an IntStream. |
"text".chars() | It streams the characters as int codes. |
Methods of Primitive Streams
| Method | Description |
|---|---|
sum() | It returns the total. |
average() | It returns the average as an OptionalDouble. |
min() / max() | It returns the smallest or largest as an OptionalInt. |
count() | It returns the number of elements. |
summaryStatistics() | It returns count, sum, min, average and max in one pass. |
boxed() | It converts to a Stream<Integer>. |
mapToObj(f) | It converts each number into an object. |
asLongStream(), asDoubleStream() | It widens to another primitive stream. |
Example: Statistics on Marks
Let's see an example that calculates statistics for a list of students.
import java.util.IntSummaryStatistics;
import java.util.List;
public class Stats {
record Student(String name, int marks) { }
public static void main(String[] args) {
List<Student> students = List.of(
new Student("Navika", 91), new Student("Srihitha", 78),
new Student("Advitha", 85), new Student("Anamaneni", 66));
int total = students.stream().mapToInt(Student::marks).sum();
double avg = students.stream().mapToInt(Student::marks)
.average().orElse(0);
int best = students.stream().mapToInt(Student::marks).max().getAsInt();
System.out.println("Total " + total + ", average " + avg
+ ", best " + best);
IntSummaryStatistics stats = students.stream()
.mapToInt(Student::marks)
.summaryStatistics();
System.out.println(stats);
}
}Total 320, average 80.0, best 91
IntSummaryStatistics{count=4, sum=320, min=66, average=80.000000, max=91}Explanation: mapToInt(Student::marks) turns the stream of students into an IntStream of marks, which has sum, average and max. average and max return optional values because the stream might be empty. summaryStatistics() computes everything in a single pass.
Example: Ranges and Converting Back
import java.util.List;
import java.util.stream.IntStream;
public class Ranges {
public static void main(String[] args) {
System.out.println(IntStream.rangeClosed(1, 10).sum());
List<Integer> evens = IntStream.rangeClosed(1, 10)
.filter(n -> n % 2 == 0)
.boxed()
.toList();
System.out.println(evens);
List<String> labels = IntStream.range(0, 3)
.mapToObj(i -> "Seat " + (i + 1))
.toList();
System.out.println(labels);
double avgLength = "Navika Srihitha".chars()
.filter(Character::isLetter)
.count() / 2.0;
System.out.println(avgLength);
}
}55
[2, 4, 6, 8, 10]
[Seat 1, Seat 2, Seat 3]
7.0Explanation: rangeClosed(1, 10).sum() adds 1 to 10. boxed() converts int values into Integer objects so they can go into a List<Integer>. mapToObj turns each index into a label. chars() gives letter codes; 14 letters across two names average 7.
Common Mistakes
Calling toList() on an IntStream. It has no toList; use boxed().toList() or toArray().
Expecting average() to return a double. It returns an OptionalDouble; use orElse(0) or getAsDouble().
Using map(Student::marks) and then looking for sum(). A Stream<Integer> has no sum; use mapToInt.
Practice
- Easy: Print the sum of the squares of the numbers from 1 to 20 using
IntStream. - Harder: Given a list of product prices as
double, print the count, minimum, maximum and average usingDoubleStream.summaryStatistics().
Key Takeaways
Was this tutorial helpful?