Course contentsShow
← Java
Lesson 1384 of 2,87031. Streams API: Creation and BasicsFree lesson

stream() Method on Collections

Learn how to create streams from any Collection using the stream() method for sequential processing.

stream() Method on Collections

You'll learn how to turn any Java Collection into a sequential stream using the built-in stream() method.

The Core Idea

Every Java Collection (List, Set, Queue, etc.) provides a stream() method that creates a sequential stream from its elements. This is the most common way to start working with the Streams API in everyday code—you simply call stream() on your existing collections and begin processing.

Think of it like this: your Collection is a parking lot full of cars, and calling stream() creates a conveyor belt that moves those cars one-by-one through a processing pipeline.

How It Works

The stream() method is defined in the Collection interface, so any class implementing Collection inherits it automatically:

List<String> languages = List.of("Java", "Python", "JavaScript");
Stream<String> languageStream = languages.stream();

Set<Integer> numbers = Set.of(1, 2, 3, 4, 5);
Stream<Integer> numberStream = numbers.stream();

Queue<String> tasks = new LinkedList<>();
tasks.add("Task A");
tasks.add("Task B");
Stream<String> taskStream = tasks.stream();

The stream produced by stream() is sequential, meaning elements are processed one after another in encounter order (for ordered collections like List).

Key Characteristics

  • Non-destructive: Calling stream() doesn't modify the original collection
  • Lazily evaluated: The stream doesn't process anything until you invoke a terminal operation
  • One-time use: Once consumed, you need to call stream() again for a new stream

Key Takeaway: The stream() method on Collections is your primary entry point into stream processing, converting any collection into a sequential stream ready for functional-style operations.