Stream Primitive Specialization

Use IntStream and mapToInt to skip boxing entirely, then convert back with boxed when object streams need the values.

JavaData Integrity

Code

snippet
import java.util.List;
import java.util.stream.IntStream;

public class PrimitiveStreams {

    public static void main(String[] args) {
        List<Integer> scores = List.of(88, 72, 95, 61, 83);

        // mapToInt:进入 IntStream,无装箱
        int total = scores.stream().mapToInt(Integer::intValue).sum();
        System.out.println("total = " + total);

        // IntStream 直接生成序列
        IntStream.rangeClosed(1, 5).forEach(i -> System.out.print(i + " "));
        System.out.println();

        // 统计 + 回到对象流
        double avg = scores.stream().mapToInt(Integer::intValue).average().orElse(0);
        List<Integer> above = scores.stream()
                .mapToInt(Integer::intValue)
                .filter(s -> s > avg)
                .boxed()
                .toList();
        System.out.printf("avg=%.1f above=%s%n", avg, above);
    }
}

How the snippet works

Stream Primitive Specialization reduces to the class PrimitiveStreams and the function main.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Using it

The run prints total =, avg= — each prefix names the step that produced it.

Key statements

double avg = scores.stream().mapToInt(Integer::intValue).average().orElse(0);
int total = scores.stream().mapToInt(Integer::intValue).sum();
List<Integer> above = scores.stream()
        .mapToInt(Integer::intValue)
        .filter(s -> s > avg)
        .boxed()
        .toList();

Interactive Tools for This Topic

FAQ

What does Stream Primitive Specialization print when run?
Execute the whole file; each printed line is prefixed with a label like `total =`, `avg=`.