Functional Programming & Streams

Primitive Streams

IntStream, LongStream, DoubleStream process numbers without boxing — plus numeric extras the object stream lacks: sum, average, range, summaryStatistics.
  • Boxed Stream<Integer> costs an object per value; IntStream streams bare ints
  • Bridges: mapToInt / mapToObj / boxed / asDoubleStream
  • IntStream.range(0, n) (exclusive) / rangeClosed(1, n) replace index loops
  • chars() on String, Random.ints(), Arrays.stream(int[]) are primitive sources
  • The specializations exist because erasure forbids Stream<int> (Generics Restrictions)
Numeric pipelines, no boxing
int total = IntStream.rangeClosed(1, 100).sum();                 // 5050

double avgLen = words.stream()
        .mapToInt(String::length)        // Stream<String> → IntStream
        .average()                        // OptionalDouble
        .orElse(0);

IntSummaryStatistics s = IntStream.of(measurements).summaryStatistics();
// s.getMin(), s.getMax(), s.getAverage(), s.getSum()

A boxed pipeline over a million ints allocates a million Integer objects (beyond the −128…127 cache) and chases a pointer per element; the primitive pipeline runs over machine words and frequently vectorizes after JIT. When a stream computes over numbers, reach for the specialization first, not as an optimization afterthought.

Sources
  • Core Java, Volume II: Advanced Features (13th ed.)Ch. 1.13 — Primitive Type Streams
  • Optimizing JavaCh. 11 — Language Performance