Java Reference ยท Streams and Functional
The IntStream interface
Reference for java.util.stream.IntStream: create int streams, use sum, average, min, max, boxed and mapToObj, and avoid boxing overhead.
IntStream is a stream of primitive int values. It exists so numeric pipelines do not wrap every number in an Integer: no boxing, less memory and faster loops. It also offers terminal operations that make sense only for numbers, such as sum(), average() and summaryStatistics().
You get an IntStream from IntStream.range(), IntStream.of(), Arrays.stream(int[]), String.chars(), or by converting with mapToInt() from an object stream. boxed() and mapToObj() convert back.
int total = IntStream.rangeClosed(1, 100).sum(); // 5050
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public interface IntStream extends BaseStream<Integer, IntStream>
| Member | Description |
|---|---|
static IntStream range(int a, int b) / rangeClosed(a, b) |
Consecutive values, end exclusive / inclusive. |
static IntStream of(int...), empty(), iterate(...), generate(...) |
Other factories. |
map, filter, flatMap, distinct, sorted, limit, skip, peek |
Intermediate operations, taking IntUnaryOperator, IntPredicate and similar. |
mapToObj, mapToLong, mapToDouble, asLongStream(), asDoubleStream(), boxed() |
Conversions. |
sum() |
int total (0 if empty). |
average() |
OptionalDouble. |
min(), max() |
OptionalInt. |
count() |
long. |
summaryStatistics() |
An IntSummaryStatistics. |
reduce, anyMatch, allMatch, noneMatch, findFirst, forEach, toArray() |
Terminal operations. |
Usage notes
- Overflow:
sum()and arithmetic wrap around silently. UseasLongStream()ormapToLongwhen totals may exceed about 2.1 billion. - Characters:
String.chars()givesintcode units, notchar. Convert with(char) cormapToObj(c -> (char) c). - No
Comparatorforsorted(): it sorts ascending. For descending order,boxed().sorted(Comparator.reverseOrder()). Optionalvariants:OptionalInthasgetAsInt(),orElse()andisPresent(), not the fullOptionalAPI.- Use for counting loops:
IntStream.range(0, n)replaces an indexedforwhen you build a result; use a normal loop when you mutate state. - Performance: primitive streams avoid allocation, but a hand-written loop is still the fastest for tiny hot paths.
- Related types:
LongStreamandDoubleStreamhave the same shape.