AI Hints
Home›Java Tutorial›Streams, filter, map and collect, More Stream Operations
Java · Lesson 104 of 120

filter, map and collect

The big three.

⏱ 2 min read▶ Video at 2:13:13🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Three stream steps do most of the work. Filter keeps some values, map changes each value, and collect gathers the results.

  • filter: keep some
  • map: change each
  • collect: gather

The big three

Filter takes a predicate, and keeps the values where it's true. Map takes a function, and turns each value into a new one. Collect gathers everything up, into a list, a string, or a map.

keyvalue
filter(p -> …)keep matching values
map(p -> …)change each value
collect(…)gather the results
toList()a shortcut for lists

A café menu

Here's a small menu, made of records. Filter keeps only drinks. Map turns each product into its name. Collect gathers the names into a list. The second stream keeps cheap items, maps them to capital names, and joins them with commas. Run it. Latte, tea, and mocha. And three items cost under three.

Main.javajava
import java.util.*;
import java.util.stream.*;
public class Main {
    record Product(String name, String type, double price) {}
    public static void main(String[] args) {
        List<Product> menu = List.of(
            new Product("Latte", "drink", 3.20), new Product("Muffin", "food", 2.50),
            new Product("Tea", "drink", 2.10), new Product("Bagel", "food", 2.90),
            new Product("Mocha", "drink", 3.60));
        List<String> drinks = menu.stream()
            .filter(p -> p.type().equals("drink"))
            .map(Product::name)
            .collect(Collectors.toList());
        System.out.println("Drinks: " + drinks);
        String cheap = menu.stream().filter(p -> p.price() < 3)
            .map(p -> p.name().toUpperCase()).collect(Collectors.joining(", "));
        System.out.println("Under 3: " + cheap);
    }
}
Output
Drinks: [Latte, Tea, Mocha]
Under 3: MUFFIN, TEA, BAGEL

Summary

Filter keeps values, map changes them, and collect gathers them. Joining makes a string. Next, more useful stream operations.

Key takeaways
  • filter
  • map
  • collect / joining
Next up: More Stream Operations — sort, count, group