Let’s explore all the different ways to create a Stream in Java — one of the most fundamental parts of using the Stream API effectively.
✅ 1. From a Collection (List, Set, etc.)
List<String> list = List.of("apple", "banana", "cherry");
Stream<String> stream = list.stream();
Stream<String> parallelStream = list.parallelStream(); // Runs in parallel
✅ 2. From Arrays
String[] array = {"one", "two", "three"};
Stream<String> stream = Arrays.stream(array);
You can also use primitive array variants:
int[] numbers = {1, 2, 3};
IntStream intStream = Arrays.stream(numbers);
✅ 3. Using Stream.of()
For a few known elements:
Stream<String> stream = Stream.of("a", "b", "c");
For a single object (boxed into a stream):
Stream<Integer> singleton = Stream.of(42);
✅ 4. From a File (Lines of Text)
Using Files.lines(Path)
:
Path path = Paths.get("example.txt");
Stream<String> lines = Files.lines(path);
⚠️ This returns a lazily-loaded Stream — must be closed!
✅ 5. Using Stream.iterate()
(Infinite Stream)
Used for generating infinite sequences — you’ll usually pair it with .limit()
.
Stream<Integer> evenNumbers = Stream.iterate(0, n -> n + 2).limit(10);
evenNumbers.forEach(System.out::println); // 0 2 4 ... 18
✅ 6. Using Stream.generate()
(Infinite Stream)
Generate values using a Supplier
:
Stream<Double> randoms = Stream.generate(Math::random).limit(5);
✅ 7. From Primitive Special Streams
IntStream intStream = IntStream.range(1, 5); // 1, 2, 3, 4
IntStream intStream2 = IntStream.rangeClosed(1, 5); // 1, 2, 3, 4, 5
LongStream longStream = LongStream.of(10L, 20L);
DoubleStream doubleStream = DoubleStream.of(3.14, 2.71);
✅ 8. From a Builder
Stream.Builder<String> builder = Stream.builder();
builder.add("a").add("b").add("c");
Stream<String> stream = builder.build();
✅ 9. From Pattern.splitAsStream()
Stream<String> stream = Pattern.compile(",").splitAsStream("a,b,c");
✅ 10. From BufferedReader.lines()
BufferedReader reader = Files.newBufferedReader(Paths.get("file.txt"));
Stream<String> lines = reader.lines();
✅ Summary Table
Source Type | Example Syntax |
---|---|
Collection | list.stream() |
Array | Arrays.stream(arr) |
Varargs | Stream.of("a", "b") |
File | Files.lines(Path) |
Infinite sequence | Stream.iterate(...) |
Random generation | Stream.generate(...) |
Primitive streams | IntStream.range(1, 10) |
Builder | Stream.builder().add(...).build() |
Regex split | Pattern.compile(",").splitAsStream(...) |
BufferedReader | reader.lines() |