Sub topic 14
Working with IntStream, LongStream, and DoubleStream
So far, most of the streams in this tutorial have held objects, such as String or Integer. Java also has three special streams made for plain numbers: IntStream, LongStream, and DoubleStream. This chapter covers what they are, why they exist, and how to use them.
Why Special Number Streams Exist
Java has two kinds of values:
- A primitive is a simple value stored directly, such as
int,long, ordouble. - An object is a value with extra structure.
Integer,Long, andDoubleare object versions of the primitives.
Generic types like Stream<T> and List<T> can only hold objects. So a Stream<Integer> holds Integer objects, not int values.
Boxing is when Java wraps a primitive inside its object version, for example turning 5 into an Integer. Unboxing is the reverse. Java does both automatically, so you rarely see them happen. They still cost time and memory, though, because every boxed number is a separate object.
A primitive stream holds raw numbers with no boxing. It also has math operations built in, such as sum() and average(), which a plain Stream<Integer> does not have.
| Stream type | Holds | Object stream it replaces |
|---|---|---|
| `IntStream` | `int` values | `Stream<Integer>` |
| `LongStream` | `long` values | `Stream<Long>` |
| `DoubleStream` | `double` values | `Stream<Double>` |
A First Example
This program adds up the squares of 1 to 5 and averages three numbers.
import java.util.stream.IntStream;
public class IntStreamExample {
public static void main(String[] args) {
int sumOfSquares = IntStream.rangeClosed(1, 5)
.map(i -> i * i)
.sum();
System.out.println(sumOfSquares); // 55
double average = IntStream.of(2, 4, 6)
.average()
.orElse(0.0);
System.out.println(average); // 4.0
}
}Here is what happens, step by step:
IntStream.rangeClosed(1, 5)makes the numbers 1, 2, 3, 4, 5.map(i -> i * i)squares each one. Each result stays anint.sum()adds them: 1 + 4 + 9 + 16 + 25 = 55.IntStream.of(2, 4, 6)makes a stream from the values you list.average()might have nothing to average, so it returns anOptionalDouble.orElse(0.0)gives a default if the stream is empty.
Creating Primitive Streams
You can get a primitive stream in several ways.
| Method | Example | Result |
|---|---|---|
| `range(a, b)` | `IntStream.range(0, 3)` | 0, 1, 2 (end not included) |
| `rangeClosed(a, b)` | `IntStream.rangeClosed(1, 3)` | 1, 2, 3 (end included) |
| `of(...)` | `DoubleStream.of(1.5, 2.5)` | 1.5, 2.5 |
| `Arrays.stream(array)` | `Arrays.stream(new int[]{4, 7})` | 4, 7 |
| `String.chars()` | `"hi".chars()` | 104, 105 (character codes) |
| `mapToInt` | `words.stream().mapToInt(String::length)` | one length per word |
Converting Between Stream Types
You will often start with a stream of objects, switch to numbers to do math, and sometimes switch back. These methods move between the types:
mapToInt,mapToLong,mapToDoubleturn an object stream into a primitive stream.boxed()turns a primitive stream back into an object stream, such asStream<Integer>.mapToObjturns each number into any object you choose.asLongStream()andasDoubleStream()widen anIntStreamto a bigger number type.
The next program uses most of these conversions.
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ConvertExample {
public static void main(String[] args) {
List<String> words = List.of("kiwi", "banana", "fig");
// Object stream to IntStream
int totalLetters = words.stream()
.mapToInt(String::length)
.sum();
System.out.println(totalLetters); // 13
// Several statistics in one pass
IntSummaryStatistics stats = words.stream()
.mapToInt(String::length)
.summaryStatistics();
System.out.println(stats.getMin()); // 3
System.out.println(stats.getMax()); // 6
System.out.println(stats.getSum()); // 13
// IntStream back to a List<Integer>
List<Integer> squares = IntStream.rangeClosed(1, 4)
.map(i -> i * i)
.boxed()
.collect(Collectors.toList());
System.out.println(squares); // [1, 4, 9, 16]
// IntStream to a stream of Strings
List<String> labels = IntStream.range(0, 3)
.mapToObj(i -> "item" + i)
.collect(Collectors.toList());
System.out.println(labels); // [item0, item1, item2]
}
}summaryStatistics() is useful when you need the count, sum, min, max, and average together. It reads the stream only once, while separate calls would need a new stream each time.
Built-in Number Operations
Primitive streams have these terminal operations ready to use:
| Operation | Return type on `IntStream` | Empty stream result |
|---|---|---|
| `sum()` | `int` | `0` |
| `count()` | `long` | `0` |
| `average()` | `OptionalDouble` | empty |
| `min()` / `max()` | `OptionalInt` | empty |
| `summaryStatistics()` | `IntSummaryStatistics` | count 0 |
OptionalInt, OptionalLong, and OptionalDouble work like the Optional you saw earlier, but they hold a primitive. To read the value, use getAsInt(), getAsLong(), or getAsDouble(), or use orElse(...) to supply a default.
import java.util.OptionalInt;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
public class OperationsExample {
public static void main(String[] args) {
OptionalInt max = IntStream.of(3, 9, 2).max();
System.out.println(max.getAsInt()); // 9
OptionalInt emptyMax = IntStream.empty().max();
System.out.println(emptyMax.isPresent()); // false
System.out.println(emptyMax.orElse(-1)); // -1
double total = DoubleStream.of(1.5, 2.5, 3.0).sum();
System.out.println(total); // 7.0
long lCount = "hello".chars()
.filter(c -> c == 'l')
.count();
System.out.println(lCount); // 2
}
}Edge Case: Overflow
An int can only hold values up to about 2.1 billion. IntStream.sum() returns an int, so a big total can overflow: it wraps around to a wrong number, and Java gives no error.
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class OverflowExample {
public static void main(String[] args) {
int wrong = IntStream.rangeClosed(1, 100_000).sum();
System.out.println(wrong); // 705082704 (wrong!)
long right = LongStream.rangeClosed(1, 100_000).sum();
System.out.println(right); // 5000050000
long alsoRight = IntStream.rangeClosed(1, 100_000)
.asLongStream()
.sum();
System.out.println(alsoRight); // 5000050000
}
}Choosing the Right Stream
- Use a primitive stream when you are doing math on numbers: sums, averages, counts, ranges.
- Use
IntStream.rangein place of a classicforloop over indexes. - Use
LongStreamfor large totals or IDs that do not fit in anint. - Use
DoubleStreamfor decimal values such as prices or measurements. Keep in mind thatdoublemath can round, for example0.1 + 0.2is not exactly0.3. For money, many programs useBigDecimalwith an object stream. - Stay with an object stream when the elements are not numbers, or when you need to keep the objects themselves.
Exercises
Exercise
You have List<String> names = List.of("Ann", "Bob", "Christina"). Write one stream expression that returns the average name length as a double, using 0.0 if the list is empty.
Show answer
names.stream().mapToInt(String::length).average().orElse(0.0). The lengths are 3, 3, and 9, so the result is 5.0. mapToInt gives an IntStream, average returns an OptionalDouble, and orElse supplies the default.
Exercise
Why does IntStream.rangeClosed(1, 3).collect(Collectors.toList()) fail to compile, and how do you fix it?
Show answer
A List holds objects, but an IntStream holds int primitives, so the object-style collect does not apply. Add boxed() first: IntStream.rangeClosed(1, 3).boxed().collect(Collectors.toList()), which gives [1, 2, 3].
Exercise
What does IntStream.range(5, 5).sum() return, and what does IntStream.range(5, 5).max() return?
Show answer
range(5, 5) is empty because the end is not included. sum() returns 0. max() returns an empty OptionalInt, so isPresent() is false.
Exercise
Write a stream expression that adds the numbers 1 to 1,000,000 and gives the correct total.
Show answer
LongStream.rangeClosed(1, 1000000).sum(), which returns 500000500000. Using IntStream.sum() would overflow, because the total is larger than the int maximum of about 2.1 billion.