Java Stream Creation

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 172 of 306

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:

SourceHow to create the stream
A collectioncollection.stream()
A mapmap.entrySet().stream(), map.keySet().stream(), map.values().stream()
An arrayArrays.stream(array), Arrays.stream(array, from, to), Stream.of(array)
Individual valuesStream.of(a, b, c), Stream.empty(), Stream.ofNullable(x)
Number rangesIntStream.range(a, b), IntStream.rangeClosed(a, b), LongStream.range(...)
A rule for the next elementStream.iterate(seed, next), Stream.iterate(seed, hasNext, next)
A generatorStream.generate(supplier), Random.ints(...)
Textstring.chars(), string.codePoints(), string.lines(), Pattern.splitAsStream(text)
Files and I/OFiles.lines(path), bufferedReader.lines(), Files.list(dir), Files.walk(dir)
DatesstartDate.datesUntil(endDate)
Combining streamsStream.concat(a, b), Stream.builder()
An Optionaloptional.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 every Collection — List, Set, Queue. The stream's order is the collection's iteration order: a list's index order, a TreeSet's sorted order, no particular order for a HashSet.
  • Maps aren't collections and have no stream() method. Stream one of their three views: entrySet() when you need keys and values together, keySet() or values() when you need only one.
  • Arrays.stream(array) streams an array; the overload with from, to streams a range (index 1 inclusive to 3 exclusive: Madurai, Salem). For an int[], it returns an IntStream, which has numeric operations like max() and sum(). (Stream.of(intArray) would produce a Stream<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 for null and a one-element stream otherwise — handy inside flatMap when 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) produces seed, 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 a for loop: it stops as soon as hasNext is false. 100, 50, 25, 12 — the next value, 6, fails n > 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 the char values of a string as ints; codePoints() streams real Unicode characters. "Hi 👋" has 5 chars but 4 code points, because the emoji takes two chars (Reader Class lesson). Use codePoints() when text may contain emoji or other supplementary characters.
  • lines() (Java 11+) splits on \n, \r\n and \r.
  • Pattern.splitAsStream splits 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 nested concat calls.
  • 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 with flatMap(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 than Files.readAllLines(path).stream() for large files.
  • Use primitive streams (IntStream, Arrays.stream(int[])) for numbers to avoid boxing.
  • Infinite sources (iterate without a condition, generate) always need something that ends them; a missing limit makes 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:

  1. start.datesUntil(end) (Java 9+) produces every date from start up to (but not including) end as a Stream<LocalDate>. A one-year range is an upper bound; the pipeline stops much earlier.
  2. Two filters keep only teaching days (an EnumSet of DayOfWeek, which makes contains fast) and drop holidays. Wednesday 25 November is a holiday, so the schedule jumps from Monday 23 to Friday 27.
  3. 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.
  4. 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).
  5. mapToObj converts each int into a formatted line; forEach(System.out::println) prints them. A fixed Locale.ENGLISH keeps 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Stream Creation and get answers drawn from it.

Signed-in readers only.