Stream Sources: Collections, Arrays, and Generators
You'll learn: Where streams originate in Java and the primary ways to create them from existing data or generate them programmatically.
The Origin Story of Streams
A stream doesn't hold data itself—it's a pipeline that processes data from somewhere else. Think of a stream like a conveyor belt in a factory: the belt doesn't store items, but it moves them from a source through various processing stations. Understanding where streams come from is your first step in mastering stream operations.
The Three Main Stream Sources
1. Collections
Any Collection (like List, Set, Queue) can produce a stream via the .stream() method. This is the most common source:
List<String> names = List.of("Alice", "Bob", "Carol");
Stream<String> nameStream = names.stream();
2. Arrays
Arrays can create streams using Arrays.stream():
String[] cities = {"Paris", "Tokyo", "Berlin"};
Stream<String> cityStream = Arrays.stream(cities);
3. Generators
Streams can be created programmatically without any existing collection. These include:
Stream.of()for specific valuesStream.generate()for infinite sequencesStream.iterate()for generated sequences with patterns
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);
Why Multiple Sources Matter
Different sources suit different scenarios. Collections work when you already have data. Arrays fit legacy code or performance-critical situations. Generators shine when you need on-demand data or infinite sequences.
Key Takeaway:
Streams originate from three primary sources: collections (via .stream()), arrays (via Arrays.stream()), and programmatic generators (via Stream factory methods)—each serving different data processing needs.