Skip to lesson

Transforming streams: practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most bugs in stream pipelines give no error at all: the list just comes out with the wrong items, in the wrong order, or one page off. They come from a few slips: steps in the wrong order, map where flatMap was needed, distinct before the data is cleaned, page maths that is off by one, and takeWhile on data that is not sorted.

Mistake 1: steps in the wrong order

Steps run top to bottom, and each sees only what the step before it produced. Most order bugs come from forgetting that.

Example 1 · Mistake: limit before sorted, filter after sorted

WrongOrderDemo.javaJava
import java.util.Comparator;import java.util.List;
record Order(String id, String status, int amount) {}
public class WrongOrderDemo {    public static void main(String[] args) {        List<Order> orders = List.of(                new Order("A1", "DELIVERED", 1200), new Order("A2", "CANCELLED", 9000),                new Order("A3", "DELIVERED", 450), new Order("A4", "DELIVERED", 7800),                new Order("A5", "DELIVERED", 3100), new Order("A6", "SHIPPED", 5000));        Comparator<Order> bigFirst = Comparator.comparing(Order::amount).reversed();
        List<String> wrong = orders.stream()                .filter(o -> o.status().equals("DELIVERED"))                .limit(2)                .sorted(bigFirst)                .map(Order::id)                .toList();        System.out.println("limit before sorted: " + wrong);
        List<String> right = orders.stream()                .filter(o -> o.status().equals("DELIVERED"))                .sorted(bigFirst)                .limit(2)                .map(Order::id)                .toList();        System.out.println("sorted before limit: " + right);    }}
Output
limit before sorted: [A1, A3]
sorted before limit: [A4, A5]

What this code does

  • The wrong pipeline takes the first two delivered orders in list order (A1 and A3) and sorts only those. A4 with Rs 7800 is never considered.
  • The fixed pipeline keeps the filter first, so only delivered orders are sorted, and limit(2) runs after sorted, so it keeps the real top two.

To check an order, read the pipeline aloud and say what the stream holds after each line: "orders", "delivered orders", "sorted by amount", "top 3", "their ids".

Three order bugs show up again and again. A filter that tests a field placed after the map that removed it does not compile. A limit placed before sorted compiles and runs, but it keeps the first N in list order, not the top N. A filter placed after sorted gives the right answer but sorts elements that are thrown away. If a line does not make sense with what came before, it is in the wrong place.

Mistake 2: map instead of flatMap, and distinct too early

When each element holds a list, such as a candidate with several skills, map(c -> c.skills()) gives a stream of lists. distinct and sorted then work on whole lists, not on skills. flatMap(c -> c.skills().stream()) gives one stream of skills.

Example 2 · Mistake: map instead of flatMap, and distinct before cleaning

SkillsDemo.javaJava
import java.util.List;
record Candidate(String name, List<String> skills) {}
public class SkillsDemo {    public static void main(String[] args) {        List<Candidate> candidates = List.of(                new Candidate("Asha", List.of("Java", "SQL")),                new Candidate("Ravi", List.of("java ", "Spring")),                new Candidate("Meena", List.of("SQL", "Python", "JAVA")));
        System.out.println("map:              " + candidates.stream()                .map(c -> c.skills())                .distinct()                .toList());
        System.out.println("flatMap only:     " + candidates.stream()                .flatMap(c -> c.skills().stream())                .distinct()                .sorted()                .toList());
        System.out.println("cleaned first:    " + candidates.stream()                .flatMap(c -> c.skills().stream())                .map(String::trim)                .map(String::toLowerCase)                .distinct()                .sorted()                .toList());    }}
Output
map:              [[Java, SQL], [java , Spring], [SQL, Python, JAVA]]
flatMap only:     [JAVA, Java, Python, SQL, Spring, java ]
cleaned first:    [java, python, spring, sql]

What this code does

  • With map, each element is a whole list, so distinct compares lists and keeps all three. flatMap gives single skills, but Java, java and JAVA still differ.
  • Trimming and lowercasing before distinct makes equal skills really equal, so each skill appears once.

distinct compares with equals, so "Java", "java" and " java " are three different Strings. Clean the values first, with map(String::trim) and map(String::toLowerCase), and only then call distinct. The same applies to records: two records are equal only when every field matches.

Mistake 3: paging that is off by one

Pages usually start at 1 in the app and in the URL. The number of items before page p is (p - 1) * size, not p * size. With p * size the first page never shows and every page is shifted by one.

Example 3 · Mistake: page maths off by one

PageBugDemo.javaJava
import java.util.List;
public class PageBugDemo {    static List<String> wrongPage(List<String> items, int page, int size) {        return items.stream().sorted().skip((long) page * size).limit(size).toList();    }
    static List<String> page(List<String> items, int page, int size) {        return items.stream().sorted().skip((long) (page - 1) * size).limit(size).toList();    }
    public static void main(String[] args) {        List<String> products = List.of("Pen", "Bag", "Lamp", "Mouse", "Bottle", "Cable", "Diary");
        System.out.println("Sorted:       " + products.stream().sorted().toList());        System.out.println("Wrong page 1: " + wrongPage(products, 1, 3));        System.out.println("Right page 1: " + page(products, 1, 3));        System.out.println("Right page 3: " + page(products, 3, 3));    }}
Output
Sorted:       [Bag, Bottle, Cable, Diary, Lamp, Mouse, Pen]
Wrong page 1: [Diary, Lamp, Mouse]
Right page 1: [Bag, Bottle, Cable]
Right page 3: [Pen]

What this code does

  • With page * size, page 1 skips the first 3 items, so the user never sees Bag, Bottle and Cable.
  • With (page - 1) * size, page 1 skips nothing. Page 3 holds the one item left, which is normal for a last page.

Paging also needs a fixed order. Without sorted, the order depends on how the data was loaded, and an item can appear on two pages or on none. Sort by a key that does not tie, or add a tie-breaker such as the name or id with thenComparing.

Mistake 4: takeWhile and dropWhile where filter was meant

takeWhile stops at the first element that fails; dropWhile starts keeping at the first element that fails. Both are only about the front of the stream. To trace one, walk the list from the left and find the first failure.

Example 4 · Tracing takeWhile and dropWhile against filter

TraceWhileDemo.javaJava
import java.util.List;
public class TraceWhileDemo {    public static void main(String[] args) {        // attendance % for each week of the term, in order        List<Integer> weekly = List.of(92, 88, 81, 72, 85, 70, 90);
        System.out.println("takeWhile(>= 75): " + weekly.stream().takeWhile(a -> a >= 75).toList());        System.out.println("dropWhile(>= 75): " + weekly.stream().dropWhile(a -> a >= 75).toList());        System.out.println("filter(>= 75):    " + weekly.stream().filter(a -> a >= 75).toList());        System.out.println("filter(< 75):     " + weekly.stream().filter(a -> a < 75).toList());    }}
Output
takeWhile(>= 75): [92, 88, 81]
dropWhile(>= 75): [72, 85, 70, 90]
filter(>= 75):    [92, 88, 81, 85, 90]
filter(< 75):     [72, 70]

What this code does

  • The first failure is 72, in week 4. takeWhile keeps the three weeks before it; dropWhile keeps 72 and every week after it, including 85 and 90.
  • filter ignores position: it finds every good week and every bad week wherever they are. "Weeks before attendance first dropped" is takeWhile; "all good weeks" is filter.

Cut at that first failure: the front part is the takeWhile result, the rest is the dropWhile result.

If the question is "every element that matches", the answer is filter. takeWhile gives the same result as filter only when the data is ordered by the tested value, such as sorted prices or a time-ordered log.

Quick test: if shuffling the input should not change the answer, you need filter, not takeWhile or dropWhile.

Finish up

Mark complete & continue

Next: forEach and count