Stream from Array Ranges with Arrays.stream(array, start, end)
You'll learn how to create streams from specific portions of an array by specifying start and end indices.
The Core Idea
Sometimes you don't need to process an entire array—you only want to work with a slice of it. The Arrays.stream() method accepts optional start (inclusive) and end (exclusive) indices, letting you create a stream from just that subrange. This is like taking a specific chapter from a book instead of reading the whole thing.
How It Works
The method signature is:
Arrays.stream(T[] array, int startInclusive, int endExclusive)
The startInclusive index tells the stream where to begin, and endExclusive marks where to stop (the element at this index is not included). This follows Java's standard half-open range convention: [start, end).
Example Usage
String[] words = {"apple", "banana", "cherry", "date", "elderberry"};
// Create stream from index 1 to 4 (excludes index 4)
Stream<String> middleWords = Arrays.stream(words, 1, 4);
// Stream contains: "banana", "cherry", "date"
middleWords.forEach(System.out::println);
This also works with primitive arrays using their specialized stream types:
int[] numbers = {10, 20, 30, 40, 50};
// Process only elements from index 2 to 4
IntStream range = Arrays.stream(numbers, 2, 4);
// Stream contains: 30, 40
int sum = range.sum(); // Result: 70
Why Use This?
Instead of creating intermediate arrays or manually copying elements, you can directly stream the exact portion you need. It's memory-efficient and expressive.
Key Takeaway: Use Arrays.stream(array, startInclusive, endExclusive) to create streams from specific array subranges, processing only the elements you need without copying data.