Creating a Stream

Streams · lesson 2 of 42 · 3 min read

Every common way to get a Stream, including infinite ones and how to bound them.

Open this lesson in the learning hub

Key points

  • collection.stream() is the everyday source. Every Collection has it.
  • Stream.of(...) for loose values, Arrays.stream(arr) for arrays.
  • IntStream.range(0, 5) counts 0 to 4 and replaces the classic index loop.
  • Stream.iterate and Stream.generate are infinite. Bound them with limit, or use the 3-arg iterate.
  • Files.lines(path) streams a file lazily, so close it with try-with-resources.

Example

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        System.out.println("of         : " + Stream.of("a", "b", "c").toList());
        System.out.println("collection : " + List.of("x", "y").stream().toList());
        System.out.println("array      : " + Arrays.stream(new int[]{1, 2, 3}).boxed().toList());
        System.out.println("range      : " + IntStream.range(0, 5).boxed().toList());
        System.out.println("empty      : " + Stream.empty().toList());
        System.out.println("chars      : " + "hi!".chars().boxed().toList());
        System.out.println("lines      : " + "one\ntwo".lines().toList());
        System.out.println("map keys   : " + Map.of("a", 1).keySet().stream().toList());

        // Infinite sources -- always bound them.
        System.out.println("iterate    : " + Stream.iterate(1, i -> i * 2).limit(5).toList());
        System.out.println("iterate3   : " + Stream.iterate(1, i -> i <= 16, i -> i * 2).toList());
        System.out.println("generate   : " + Stream.generate(() -> "hi").limit(3).toList());
    }
}

Stream the source you already have; never build a list just to stream it.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Streams course, and every lesson in it is listed on the Streams contents page.