Sub topic 5
Selecting and Transforming Elements with filter and map
Most stream work comes down to two jobs. You pick the elements you want, and you change them into the form you need. The filter operation does the first job. The map operation does the second. This chapter shows how each one works, how to chain them, and the mistakes beginners often make with them.
What filter Does
filter is an intermediate operation. An intermediate operation is a step that takes a stream and gives back a new stream. It does not produce a final result by itself.
filter takes a predicate. A predicate is a function that gets one element and returns true or false. Elements that return true stay in the stream. Elements that return false are dropped.
filter never changes an element. Each element that passes comes out exactly as it went in. The stream may get shorter, but it never gets longer.
What map Does
map is also an intermediate operation. It takes a function and applies it to every element. The stream after map holds the results of that function.
map is one-to-one. One element goes in, and exactly one element comes out. So the stream after map always has the same number of elements as the stream before it. Only the values change.
Your First filter and map Pipeline
Here is a complete program. It keeps names longer than three characters and turns them into upper case.
import java.util.List;
import java.util.stream.Collectors;
public class FilterMapExample {
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]
}
}Here is what each line does:
names.stream()creates a stream from the list.filter(name -> name.length() > 3)keepsalice,carol, anddave. It dropsbob.map(String::toUpperCase)changes each kept name to upper case.String::toUpperCaseis a method reference. It means the same asname -> name.toUpperCase().collect(Collectors.toList())gathers the results into a new list. A later chapter covers collectors in detail.
map Can Change the Type
The function you pass to map can return a different type than it receives. A stream of String can become a stream of Integer.
import java.util.List;
import java.util.stream.Collectors;
public class MapTypeExample {
public static void main(String[] args) {
List<String> words = List.of("sun", "moon", "stars");
List<Integer> lengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println(lengths); // [3, 4, 5]
}
}The input is Stream<String>. After map(String::length), it is Stream<Integer>. Java works out the new type for you from the function's return type.
Working with Your Own Objects
Real programs often stream over objects. In this example, a store has products. We want the names of products that are in stock and cost less than 20.
import java.util.List;
import java.util.stream.Collectors;
public class ProductExample {
static class Product {
private final String name;
private final double price;
private final boolean inStock;
Product(String name, double price, boolean inStock) {
this.name = name;
this.price = price;
this.inStock = inStock;
}
String getName() { return name; }
double getPrice() { return price; }
boolean isInStock() { return inStock; }
}
public static void main(String[] args) {
List<Product> products = List.of(
new Product("Pen", 1.50, true),
new Product("Lamp", 35.00, true),
new Product("Mug", 8.00, false),
new Product("Book", 12.00, true));
List<String> cheapInStock = products.stream()
.filter(Product::isInStock)
.filter(p -> p.getPrice() < 20)
.map(Product::getName)
.collect(Collectors.toList());
System.out.println(cheapInStock); // [Pen, Book]
}
}This pipeline uses two filter steps in a row. An element must pass both to stay. You could also write one filter: filter(p -> p.isInStock() && p.getPrice() < 20). Both give the same result. Separate filters are often easier to read, since each line states one rule.
The final map(Product::getName) turns each Product into its String name. The result is a List<String>, not a List<Product>.
Order Matters
Steps run in the order you write them. Each step only sees what the step before it produced. Compare these two pipelines on the list ["alice", "bob", "carol"]:
| Pipeline | Result | Why |
|---|---|---|
| `filter(s -> s.length() > 3).map(String::length)` | `[5, 5]` | Names are checked first, then turned into lengths. |
| `map(String::length).filter(n -> n > 3)` | `[5, 5]` | Same numbers, but the filter now works on `Integer` values. |
| `map(String::length).filter(s -> s.startsWith("a"))` | Does not compile | After `map`, the elements are `Integer`, which has no `startsWith` method. |
Once you map to a new type, later steps can only use the new type. If you still need the original value, filter before you map.
Order can also affect speed. Filtering first means map runs on fewer elements. If the mapping work is costly, put cheap filters early.
The Original Collection Does Not Change
Streams do not modify their source. After the pipeline runs, the original list still holds the same elements.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class SourceUnchangedExample {
public static void main(String[] args) {
List<String> colors = new ArrayList<>(List.of("red", "green", "blue"));
List<String> upper = colors.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(colors); // [red, green, blue]
System.out.println(upper); // [RED, GREEN, BLUE]
}
}map builds new values. It does not write them back into colors. If you want to keep the changes, store the result in a variable, as the code does with upper.
Common Mistakes
- Forgetting the terminal operation. A terminal operation is the last step that produces a result, such as
collect. Without one,filterandmapnever run.names.stream().map(String::toUpperCase);does nothing useful. - Returning null from map. If your function returns
null, the stream will containnull. A later step that calls a method on it will throw aNullPointerException. Filter out bad values first, for example withfilter(s -> s != null). - Trying to make map drop elements.
mapalways produces one output per input. To drop elements, usefilter. - Changing objects inside map. Code like
map(p -> { p.setPrice(0); return p; })changes the original objects. That surprises readers and causes bugs. Return new values instead of editing old ones.
Summary
filterkeeps elements whose predicate returnstrue. It never changes them.mapchanges every element with a function. It keeps the count the same and can change the type.- You can chain several
filterandmapsteps. They run in the order written. - Neither step changes the source collection. Nothing runs until a terminal operation is called.
Exercise
Given List.of("cat", "horse", "ox", "zebra"), write a pipeline that keeps words with more than two letters and turns each into its length. What list does it produce?
Show answer
words.stream().filter(w -> w.length() > 2).map(String::length).collect(Collectors.toList()) produces [3, 5, 5]. The word "ox" is dropped by filter, and the other three are mapped to their lengths.
Exercise
A learner writes names.stream().map(String::length).filter(n -> n.startsWith("a")). Why does this fail to compile, and how do you fix it?
Show answer
After map(String::length), the stream holds Integer values, and Integer has no startsWith method. Move the filter before the map: names.stream().filter(n -> n.startsWith("a")).map(String::length).
Exercise
Can map ever make a stream shorter? Which operation should you use to drop elements?
Show answer
No. map is one-to-one, so the output always has the same number of elements as the input. Use filter to drop elements.