Arrays.stream() for Array-to-Stream Conversion
You'll learn how to convert arrays into streams using Arrays.stream(), including specialized variants for primitive arrays.
What Is Arrays.stream()?
While Collection.stream() works for collections, arrays need their own conversion method. The Arrays.stream() static method from java.util.Arrays transforms any array—reference type or primitive—into a stream, bridging the gap between traditional array-based code and modern stream processing.
Think of it like converting a static shelf of books (an array) into a conveyor belt (a stream) where you can inspect, filter, and transform each item as it passes by.
Basic Array Conversion
For reference type arrays:
String[] names = {"Alice", "Bob", "Charlie"};
Stream<String> nameStream = Arrays.stream(names);
// Process the stream
nameStream.filter(name -> name.startsWith("A"))
.forEach(System.out::println); // Alice
Primitive Array Specializations
Arrays.stream() is overloaded for primitive arrays, returning specialized streams (IntStream, LongStream, DoubleStream) to avoid boxing overhead:
int[] numbers = {1, 2, 3, 4, 5};
IntStream intStream = Arrays.stream(numbers);
double average = intStream.average().orElse(0.0);
System.out.println(average); // 3.0
Partial Array Conversion
You can specify start (inclusive) and end (exclusive) indices:
int[] array = {10, 20, 30, 40, 50};
IntStream partialStream = Arrays.stream(array, 1, 4); // 20, 30, 40
partialStream.forEach(System.out::println);
This is useful when you only need to process a subset of array elements without creating a new array.
Key Takeaway: Use Arrays.stream() to convert arrays into streams—it automatically chooses specialized primitive streams (IntStream, LongStream, DoubleStream) for primitive arrays and supports partial array ranges with overloaded variants.