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;IntStreamstreams bare ints - Bridges:
mapToInt/mapToObj/boxed/asDoubleStream IntStream.range(0, n)(exclusive) /rangeClosed(1, n)replace index loopschars()on String,Random.ints(),Arrays.stream(int[])are primitive sources- The specializations exist because erasure forbids
Stream<int>(Generics Restrictions)
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.