Stream Primitive Specialization
Use IntStream and mapToInt to skip boxing entirely, then convert back with boxed when object streams need the values.
Code
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
HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Stream Primitive Specialization print when run?
- Execute the whole file; each printed line is prefixed with a label like `total =`, `avg=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.