Course contentsShow
← Java
Lesson 1482 of 2,87032. Streams API: Intermediate OperationsFree lesson

Combining map and filter

The common pattern of filtering elements then transforming survivors, and why order matters for performance.

Combining map and filter

What you'll learn: Why chaining filter before map often performs better than the reverse, and how to combine these operations effectively.

The Common Pattern

When working with streams, you'll frequently need to filter out unwanted elements and then transform what remains. Both orderings work correctly, but one is usually more efficient.

Why Order Matters

Think of it like preparing fruit: Would you rather peel 100 apples then throw away 90 rotten ones, or inspect 100 apples, discard the 90 bad ones, and only peel the 10 good ones you're keeping?

Filter before map means fewer transformations:

List<String> names = List.of("Alice", "Bob", "Alexander", "Amanda", "Charlie");

// Efficient: filter first (5 → 3 elements), then transform (3 elements)
List<String> result = names.stream()
    .filter(name -> name.startsWith("A"))  // 3 elements pass
    .map(String::toUpperCase)               // Transform only 3
    .toList();
// [ALICE, ALEXANDER, AMANDA]

Map before filter wastes work:

// Less efficient: transform all (5 elements), then filter (5 → 3 elements)
List<String> result = names.stream()
    .map(String::toUpperCase)               // Transform all 5
    .filter(name -> name.startsWith("A"))  // Then filter
    .toList();
// Same result, more work done

When Map-Then-Filter Makes Sense

Sometimes you must transform first because the filter depends on the transformation:

List<String> numbers = List.of("1", "abc", "42", "xyz");

List<Integer> result = numbers.stream()
    .map(s -> s.length())           // Transform to lengths
    .filter(len -> len > 2)         // Filter based on transformed value
    .toList();
// [3, 3]

Key Takeaway: Prefer filter before map when possible—it reduces the number of transformations performed. Only use map first when the filter logic depends on the transformed values.