Java Stream Creation
Where Streams Come From
Every stream pipeline starts with a source. Java offers many ways to create one, grouped by where the data comes from:
| Source | How to create the stream |
|---|---|
| A collection | collection.stream() |
| A map | map.entrySet().stream(), map.keySet().stream(), map.values().stream() |
| An array | Arrays.stream(array), Arrays.stream(array, from, to), Stream.of(array) |
| Individual values | Stream.of(a, b, c), Stream.empty(), Stream.ofNullable(x) |
| Number ranges | IntStream.range(a, b), IntStream.rangeClosed(a, b), LongStream.range(...) |
| A rule for the next element | Stream.iterate(seed, next), Stream.iterate(seed, hasNext, next) |
| A generator | Stream.generate(supplier), Random.ints(...) |
| Text | string.chars(), string.codePoints(), string.lines(), Pattern.splitAsStream(text) |
| Files and I/O | Files.lines(path), bufferedReader.lines(), Files.list(dir), Files.walk(dir) |
| Dates | startDate.datesUntil(endDate) |
| Combining streams | Stream.concat(a, b), Stream.builder() |
An Optional | optional.stream() |
Choosing the right source keeps pipelines short and avoids creating temporary collections only to stream over them.
Streams from Collections, Maps, Arrays and Values
import java.util.*;
import java.util.stream.*;
public class C1 {
public static void main(String[] args) {
List<String> list = List.of("Java", "Django", "Docker");
Set<Integer> set = new TreeSet<>(Set.of(3, 1, 2));
Map<String, Integer> fees = new TreeMap<>(Map.of("JAVA", 4999, "PY", 2999));
String[] cities = {"Chennai", "Madurai", "Salem", "Trichy"};
int[] marks = {91, 45, 78};
System.out.println(list.stream().map(String::length).toList());
System.out.println(set.stream().map(n -> n * 10).toList());
System.out.println(fees.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).toList());
System.out.println(fees.keySet().stream().toList() + " " + fees.values().stream().mapToInt(Integer::intValue).sum());
System.out.println(Arrays.stream(cities).filter(c -> c.length() > 5).toList());
System.out.println(Arrays.stream(cities, 1, 3).toList());
System.out.println(Arrays.stream(marks).max().getAsInt());
System.out.println(Stream.of("a", "b", "c").count() + " " + Stream.empty().count());
String maybe = null;
System.out.println(Stream.ofNullable(maybe).count() + " " + Stream.ofNullable("x").count());
}
}
Output:
[4, 6, 6]
[10, 20, 30]
[JAVA=4999, PY=2999]
[JAVA, PY] 7998
[Chennai, Madurai, Trichy]
[Madurai, Salem]
91
3 0
0 1
collection.stream()works for everyCollection—List,Set,Queue. The stream's order is the collection's iteration order: a list's index order, aTreeSet's sorted order, no particular order for aHashSet.- Maps aren't collections and have no
stream()method. Stream one of their three views:entrySet()when you need keys and values together,keySet()orvalues()when you need only one. Arrays.stream(array)streams an array; the overload withfrom, tostreams a range (index 1 inclusive to 3 exclusive:Madurai,Salem). For anint[], it returns anIntStream, which has numeric operations likemax()andsum(). (Stream.of(intArray)would produce aStream<int[]>with a single element — the whole array — a common surprise.)Stream.of(...)creates a stream from the given values;Stream.empty()an empty stream, useful as a default return value.Stream.ofNullable(x)(Java 9+) gives an empty stream fornulland a one-element stream otherwise — handy insideflatMapwhen some values may be missing.
Number Ranges and Generated Streams
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.*;
public class C2 {
public static void main(String[] args) {
System.out.println(IntStream.range(0, 5).boxed().toList() + " " + IntStream.rangeClosed(1, 5).sum());
System.out.println(Stream.iterate(1, n -> n * 3).limit(6).toList());
System.out.println(Stream.iterate(100, n -> n > 10, n -> n / 2).toList());
System.out.println(Stream.iterate(new int[] {0, 1}, f -> new int[] {f[1], f[0] + f[1]})
.limit(10).map(f -> f[0]).toList());
AtomicInteger seq = new AtomicInteger(1000);
System.out.println(Stream.generate(() -> "INV-" + seq.incrementAndGet()).limit(3).toList());
System.out.println(new Random(7).ints(5, 1, 7).boxed().toList());
System.out.println("hello".chars().mapToObj(c -> String.valueOf((char) c)).toList());
System.out.println("Hi 👋".codePoints().count() + " code points, " + "Hi 👋".chars().count() + " chars");
System.out.println("line one\nline two\r\nline three".lines().toList());
System.out.println(java.util.regex.Pattern.compile("\\s*,\\s*").splitAsStream("pen , ink,bag").toList());
Stream<String> a = Stream.of("x", "y"), b = Stream.of("z");
System.out.println(Stream.concat(a, b).toList());
Stream.Builder<String> builder = Stream.builder();
builder.add("first").add("second");
if (args.length == 0) builder.add("optional third");
System.out.println(builder.build().toList());
System.out.println(Optional.of("present").stream().toList() + " " + Optional.empty().stream().count());
}
}
Output:
[0, 1, 2, 3, 4] 15
[1, 3, 9, 27, 81, 243]
[100, 50, 25, 12]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[INV-1001, INV-1002, INV-1003]
[5, 3, 4, 5, 5]
[h, e, l, l, o]
4 code points, 5 chars
[line one, line two, line three]
[pen, ink, bag]
[x, y, z]
[first, second, optional third]
[present] 0
Ranges
IntStream.range(0, 5) produces 0 to 4 (end exclusive, like a for loop's i < 5); rangeClosed(1, 5) includes the end. They're the stream equivalent of a counting loop, often used to process indexes. boxed() converts an IntStream into a Stream<Integer> so it can be collected into a List.
iterate
Stream.iterate(seed, next)producesseed,next(seed),next(next(seed)), ... forever —1, 3, 9, 27, .... It must be limited (limit,takeWhile) or ended by a short-circuiting terminal operation.Stream.iterate(seed, hasNext, next)(Java 9+) works like aforloop: it stops as soon ashasNextis false.100, 50, 25, 12— the next value, 6, failsn > 10.- The Fibonacci example iterates over pairs stored in a small array, then maps each pair to its first number — a common trick when each element depends on the previous two.
generate
Stream.generate(supplier) calls the supplier for every element. It's used for random values, unique IDs, or repeating a value. The supplier here uses an AtomicInteger, which is safe to update from a lambda. Random.ints(count, from, to) produces random numbers directly as an IntStream; a fixed seed (7) makes the sequence repeatable, which is useful in tests.
Text
chars()streams thecharvalues of a string asints;codePoints()streams real Unicode characters."Hi 👋"has 5chars but 4 code points, because the emoji takes twochars (Reader Class lesson). UsecodePoints()when text may contain emoji or other supplementary characters.lines()(Java 11+) splits on\n,\r\nand\r.Pattern.splitAsStreamsplits by a regular expression — here, commas with optional spaces around them.
Combining
Stream.concat(a, b)joins two streams. For more than two,Stream.of(a, b, c).flatMap(s -> s)is clearer than nestedconcatcalls.Stream.builder()adds elements one at a time, including conditionally, before building the stream.Optional.stream()(Java 9+) gives a one-element or empty stream, so optional values can join a pipeline withflatMap(Optional::stream).
Streams from Files and Directories
import java.io.*;
import java.nio.file.*;
import java.util.stream.*;
public class Files1 {
public static void main(String[] args) throws IOException {
Path log = Files.writeString(Path.of("app.log"), "INFO start\nERROR db\nINFO ok\nERROR disk\n");
try (Stream<String> lines = Files.lines(log)) {
System.out.println(lines.filter(l -> l.startsWith("ERROR")).count() + " errors");
}
try (BufferedReader r = Files.newBufferedReader(log)) {
System.out.println(r.lines().map(l -> l.split(" ")[0]).distinct().toList());
}
Files.createDirectories(Path.of("docs/a"));
Files.writeString(Path.of("docs/a/x.md"), "#");
Files.writeString(Path.of("docs/y.md"), "#");
try (Stream<Path> files = Files.walk(Path.of("docs"))) {
System.out.println(files.filter(p -> p.toString().endsWith(".md")).map(Path::toString).sorted().toList());
}
}
}
Output (on Linux or macOS):
2 errors
[INFO, ERROR]
[docs/a/x.md, docs/y.md]
Files.lines, Files.list and Files.walk return streams that hold open file handles, so they must be closed — always use try-with-resources. They read lazily, so even a multi-gigabyte log file is processed with constant memory. bufferedReader.lines() streams from a reader you already have; closing the reader closes the source.
Choosing the Right Source
- Don't build a collection only to stream it:
IntStream.rangeClosed(1, 100)rather than a loop that fills a list;Files.lines(path)rather thanFiles.readAllLines(path).stream()for large files. - Use primitive streams (
IntStream,Arrays.stream(int[])) for numbers to avoid boxing. - Infinite sources (
iteratewithout a condition,generate) always need something that ends them; a missinglimitmakes the program run forever or run out of memory. - Streams from resources (files, directories, database cursors) must be closed.
Practical Example: Generating a Class Schedule
A course runs on Mondays, Wednesdays and Fridays, skipping public holidays, until twelve sessions have been scheduled. Each session covers part of a module. Instead of a loop with counters and date arithmetic, the schedule is generated from a stream of dates.
import java.time.*;
import java.time.format.*;
import java.util.*;
import java.util.stream.*;
public class Schedule {
static List<LocalDate> classDates(LocalDate start, int sessions, Set<DayOfWeek> days, Set<LocalDate> holidays) {
return start.datesUntil(start.plusYears(1))
.filter(d -> days.contains(d.getDayOfWeek()))
.filter(d -> !holidays.contains(d))
.limit(sessions)
.toList();
}
public static void main(String[] args) {
Set<LocalDate> holidays = Set.of(LocalDate.of(2026, 11, 25), LocalDate.of(2026, 12, 25));
List<LocalDate> dates = classDates(LocalDate.of(2026, 11, 16), 12,
EnumSet.of(DayOfWeek.MONDAY, DayOfWeek.WEDNESDAY, DayOfWeek.FRIDAY), holidays);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE dd MMM", Locale.ENGLISH);
List<String> modules = List.of("Streams", "Collectors", "Optional", "Concurrency");
IntStream.range(0, dates.size())
.mapToObj(i -> String.format("%2d. %s %s (part %d)", i + 1, dates.get(i).format(fmt),
modules.get(i / 3), i % 3 + 1))
.forEach(System.out::println);
System.out.println("course ends " + dates.get(dates.size() - 1));
}
}
Output:
1. Mon 16 Nov Streams (part 1)
2. Wed 18 Nov Streams (part 2)
3. Fri 20 Nov Streams (part 3)
4. Mon 23 Nov Collectors (part 1)
5. Fri 27 Nov Collectors (part 2)
6. Mon 30 Nov Collectors (part 3)
7. Wed 02 Dec Optional (part 1)
8. Fri 04 Dec Optional (part 2)
9. Mon 07 Dec Optional (part 3)
10. Wed 09 Dec Concurrency (part 1)
11. Fri 11 Dec Concurrency (part 2)
12. Mon 14 Dec Concurrency (part 3)
course ends 2026-12-14
How it works:
start.datesUntil(end)(Java 9+) produces every date fromstartup to (but not including)endas aStream<LocalDate>. A one-year range is an upper bound; the pipeline stops much earlier.- Two filters keep only teaching days (an
EnumSetofDayOfWeek, which makescontainsfast) and drop holidays. Wednesday 25 November is a holiday, so the schedule jumps from Monday 23 to Friday 27. limit(sessions)stops after twelve matching dates. Because streams are lazy, only the dates up to 14 December are ever examined — the rest of the year is never generated.IntStream.range(0, dates.size())streams the session indexes, which is the standard way to work with positions in a stream: the index gives the session number (i + 1), the module (i / 3— three sessions per module) and the part within the module (i % 3 + 1).mapToObjconverts eachintinto a formatted line;forEach(System.out::println)prints them. A fixedLocale.ENGLISHkeeps day and month names the same on every machine.
Changing the rules — two sessions a week, a different holiday list, twenty sessions — means changing an argument, not rewriting loop logic.