Course contentsShow
← Java
Lesson 1388 of 2,87031. Streams API: Creation and BasicsFree lesson

IntStream, LongStream, DoubleStream from Primitive Arrays

Work with specialized primitive streams created from int[], long[], and double[] arrays for better performance.

IntStream, LongStream, DoubleStream from Primitive Arrays

What you'll learn: How to create specialized primitive streams directly from int[], long[], and double[] arrays for better performance and memory efficiency.

Why Specialized Primitive Streams Matter

When working with primitive arrays, you could box each element into Integer, Long, or Double objects and use a regular Stream<T>. But that's wasteful! Java provides specialized stream types—IntStream, LongStream, and DoubleStream—that work directly with primitive values, avoiding the overhead of boxing and unboxing.

Think of it like shipping packages: boxing primitives is like wrapping each item individually in bubble wrap before loading the truck. Primitive streams skip that extra packaging and handle the raw items directly—faster and more efficient.

Creating Primitive Streams from Arrays

Use the Arrays.stream() method with primitive arrays:

int[] numbers = {1, 2, 3, 4, 5};
IntStream intStream = Arrays.stream(numbers);

long[] longs = {100L, 200L, 300L};
LongStream longStream = Arrays.stream(longs);

double[] doubles = {1.5, 2.5, 3.5};
DoubleStream doubleStream = Arrays.stream(doubles);

Each specialized stream type offers primitive-specific operations like sum(), average(), max(), and min() that work directly with primitive values—no boxing required.

Performance Benefits

Using primitive streams avoids:

  • Memory overhead of wrapper objects
  • CPU cycles spent boxing/unboxing
  • Garbage collection pressure from temporary wrapper objects

For large datasets or performance-critical code, this difference is significant.

Key Takeaway: Use Arrays.stream() with primitive arrays to create IntStream, LongStream, or DoubleStream instead of boxing to Stream<Integer>, Stream<Long>, or Stream<Double>—you'll get better performance and access to specialized primitive operations.