Sub topic 2
What Is a Stream?
Java programs often work with groups of data: a list of names, a set of prices, a map of orders. Before Java 8, you processed these groups with loops. Java 8 added the Stream API, which gives you another way to do it. This chapter explains what a stream is, how it differs from a collection, and why you would use one.
The Problem Streams Solve
Say you have a list of names and want the ones longer than three letters, in upper case. Here is the classic loop version.
import java.util.ArrayList;
import java.util.List;
public class LoopVersion {
public static void main(String[] args) {
List<String> names = List.of("alice", "bob", "carol", "dave");
List<String> result = new ArrayList<>();
for (String name : names) {
if (name.length() > 3) {
result.add(name.toUpperCase());
}
}
System.out.println(result); // [ALICE, CAROL, DAVE]
}
}This works. But you have to read every line to see what it does. You create an empty list, loop, check, convert, and add. The goal ("keep long names, make them upper case") is mixed in with the mechanics of the loop.
Here is the same task with a stream.
import java.util.List;
import java.util.stream.Collectors;
public class StreamVersion {
public static void main(String[] args) {
List<String> names = List.of("alice", "bob", "carol", "dave");
List<String> result = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(result); // [ALICE, CAROL, DAVE]
}
}Each line states one step: keep the long names, convert them, gather them into a list. You describe what you want, and the stream works out how to loop. This style is called declarative code. Code that spells out every step, like the loop above, is called imperative code.
A Definition
A stream is a sequence of elements that you process one step at a time. An element is one item in the sequence, such as one name in a list.
A stream does not hold data the way a list does. It is more like a conveyor belt. Items come onto the belt from a source, which is where the data comes from, such as a list. Each station along the belt does one job, like removing items or changing them. At the end, something collects the results.
This chain of steps is called a pipeline. A later chapter covers the parts of a pipeline in detail. For now, remember that a pipeline starts at a source, passes through steps, and ends with a result.
Streams Versus Collections
A collection is an object that stores a group of elements, such as a List, Set, or Map. Streams and collections both deal with groups of elements, but they have different jobs.
| Feature | Collection | Stream |
|---|---|---|
| Main purpose | Store data | Process data |
| Holds elements in memory | Yes | No, it pulls them from a source |
| Can be changed (add, remove) | Often yes | No |
| Can be used many times | Yes | No, only once |
| Does work right away | Yes | No, only when a result is asked for |
| Can be endless | No | Yes |
The sections below explain each difference.
A stream does not store data
A list keeps its elements in memory. You can ask for the third one at any time. A stream has no storage of its own. It reads elements from its source as they are needed and passes them along. You cannot ask a stream for "element number three."
A stream does not change its source
When you filter or map a stream, the original list stays the same. The stream produces new results and leaves the source alone.
import java.util.List;
import java.util.stream.Collectors;
public class SourceUnchanged {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4);
List<Integer> doubled = numbers.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
System.out.println(numbers); // [1, 2, 3, 4]
System.out.println(doubled); // [2, 4, 6, 8]
}
}The numbers list still holds 1, 2, 3, 4. The doubled values went into a new list.
A stream can be used only once
When a stream produces its result, it is finished. We say it has been consumed. If you need to process the same data again, you make a new stream from the source by calling stream() again. A later chapter on common mistakes shows what happens if you forget.
A stream is lazy
Lazy means the stream does no work until you ask for a final result. The steps in the middle only describe the work. Nothing runs until the end of the pipeline asks for data. Because of this, a stream can skip work it does not need. The chapter "Why Streams Are Lazy" shows this in action.
A stream can be endless
A list must have a fixed number of elements. A stream can describe an endless sequence, such as "1, 2, 4, 8, ..." forever. Laziness makes this safe, because the stream only makes as many elements as you ask for. A later chapter covers these infinite streams.
Where Streams Come From
Streams live in the java.util.stream package. The main type is Stream<T>. The T is a type parameter, a placeholder for the kind of element. A Stream<String> carries strings, and a Stream<Integer> carries integers.
The most common way to get a stream is to call stream() on a collection:
import java.util.List;
import java.util.stream.Stream;
public class FirstStream {
public static void main(String[] args) {
List<String> fruits = List.of("apple", "banana", "cherry");
Stream<String> fruitStream = fruits.stream();
System.out.println(fruitStream.count()); // 3
}
}Here count() asks the stream how many elements it has. That request ends the pipeline. Arrays, single values, and other sources can produce streams too. The chapter "Creating Streams from Collections, Arrays, and Values" covers them.
When to Use a Stream
Streams work well when you want to:
- Select some elements from a group.
- Change each element into something else.
- Sort, count, or combine elements.
- Build a new list, set, map, or string from the results.
A plain loop can still be the better choice when:
- You need to change the original collection while you go through it.
- You need to break out of a loop early in a complex way, or jump around by index.
- The logic has many steps that depend on each other, so a stream would be harder to read.
Summary
- A stream is a sequence of elements that you process in steps.
- A stream reads from a source but does not store or change it.
- A stream is consumed once, does no work until a result is requested, and can even be endless.
- Stream code describes what to do, which often makes it shorter and clearer than a loop.
Exercise
You have List<String> colors = List.of("red", "green", "blue");. You run colors.stream().map(String::toUpperCase).collect(Collectors.toList());. What does colors contain afterward, and why?
Show answer
It still contains ["red", "green", "blue"]. A stream does not change its source. The upper-case values go into a new list returned by collect.
Exercise
Name three differences between a List and a Stream.
Show answer
Any three of these: a list stores its elements in memory and a stream does not; a list can be changed and a stream cannot; a list can be used many times and a stream only once; a list does its work right away and a stream is lazy; a list has a fixed size and a stream can be endless.
Exercise
Rewrite this loop as a stream pipeline: create an empty ArrayList called result, then for each Integer n in List.of(5, 12, 8, 20), if n > 10, add n * 10 to result.
Show answer
List<Integer> result = List.of(5, 12, 8, 20).stream().filter(n -> n > 10).map(n -> n * 10).collect(Collectors.toList()); The result is [120, 200].