Memra

Primitive streams: IntStream, LongStream, DoubleStream

Avoiding boxing, computing statistics, and converting between stream types.

Avoiding the boxing tax

A Stream<Integer> autoboxes every element — expensive for large numeric pipelines. Java provides three primitive specialisations:

| Stream | Element type | |---|---| | IntStream | int | | LongStream | long | | DoubleStream | double |

They gain numeric operations that generic streams don't have:

IntStream.range(1, 6)          // 1, 2, 3, 4, 5 (exclusive end)
    .filter(n -> n % 2 == 0)
    .forEach(System.out::println); // 2 4

int sum  = IntStream.rangeClosed(1, 10).sum();        // 55
double avg = IntStream.of(1, 2, 3, 4).average().getAsDouble(); // 2.5

IntSummaryStatistics stats = IntStream.of(3, 1, 4, 1, 5, 9)
    .summaryStatistics();
stats.getMin();   // 1
stats.getMax();   // 9
stats.getSum();   // 23
stats.getAverage(); // 3.833...

Converting between stream types:

// object stream → primitive stream
Stream<String> names = Stream.of("Alice", "Bob");
IntStream lengths = names.mapToInt(String::length);  // 5, 3

// primitive stream → object stream
Stream<Integer> boxed = IntStream.range(0, 3).boxed(); // boxes ints

mapToInt / mapToLong / mapToDouble convert a Stream<T> to a primitive stream. boxed() converts a primitive stream back to an object stream. mapToObj(Function) maps to an arbitrary object type.

NORMAL ~/memra/learn/java-from-zero/primitive-streams utf-8 LF