Skip to content
Tutorials Center
My learning

Topics

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.

Java
int total = IntStream.rangeClosed(1, 100).sum();   // 5050

Try it

Java Creating and reducing

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.

Java Converting between int and objects

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

Java
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. Use asLongStream() or mapToLong when totals may exceed about 2.1 billion.
  • Characters: String.chars() gives int code units, not char. Convert with (char) c or mapToObj(c -> (char) c).
  • No Comparator for sorted(): it sorts ascending. For descending order, boxed().sorted(Comparator.reverseOrder()).
  • Optional variants: OptionalInt has getAsInt(), orElse() and isPresent(), not the full Optional API.
  • Use for counting loops: IntStream.range(0, n) replaces an indexed for when 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: LongStream and DoubleStream have the same shape.