stream()
- Java course
- Intermediate
- Lesson 106/116
- 5 min
Learn to create streams from collections with stream().
The Stream<T> interface
Stream<T> is an interface that supports sequential or parallel operations on a collection. Calling list.stream() returns a Stream; it does not modify the collection itself.
Stream operations split into two: intermediate operations return a new Stream and run lazily; terminal operations consume the stream and produce a result. A Stream can be consumed only once; a second use throws IllegalStateException.
Laziness and single use
Intermediate operations do not run immediately; the pipeline starts only when a terminal operation is called. This is known as lazy evaluation. list.stream().filter(x -> x > 0) alone does nothing; adding a terminal like .count() triggers execution.
Once a Stream is consumed it cannot be reused. If a new stream is needed, you call stream() on the collection again. This condition holds regardless of the stream source.
Practice Count with a Stream
Declare List<String> names = new ArrayList<>();; add "Ayşe", "Alex", "Mehmet". Compute the count with long count = names.stream().count();. Print it with System.out.println(count);.
Starter code
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Declare List<String>, add three names, count with stream().count(), print
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ayşe");
names.add("Alex");
names.add("Mehmet");
long count = names.stream().count();
System.out.println(count);
}
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does list.stream() return?
- A new List
- An Iterator
- An empty array
- A Stream<T> Correct answer
Explanation: stream() returns a Stream<T>; the original list is unchanged.
2 Complete the Stream call
Stream<String> s = names.____();
Stream<String> s = names.stream();
Explanation: The stream() method returns a Stream from a List.
3 Match the Stream concepts
| Term | Meaning |
|---|---|
stream() |
Starts a stream |
intermediate |
Returns a new Stream |
terminal |
Consumes the stream |
lazy |
Lazy evaluation |