Streams and Functional Interfaces

Lazy pipelines built from lambdas.

6 lessons · 17 past questions · 97 marks in the papers collected here

Open the interactive lessons →Streams and Functional Interfaces past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Lambdas and functional interfaces
  2. Pipelines and laziness
  3. filter versus map
  4. iterate and size control
  5. takeWhile, dropWhile and filter
  6. Equivalent pipelines

1. Lambdas and functional interfaces

Sometimes the thing you want to pass in is not a value but a rule.

how to hand a piece of behaviour to a method

A courier has a list of parcel weights. Today the question is "how many are heavy?". Tomorrow it is "how many are tiny?". The loop is the same each time. Only the rule inside the if changes. Can we write the loop once and hand the rule in?

Think of a coffee grinder with a blade you can swap. The machine does the turning; you choose the blade. The analogy stops here: in Java the blade must fit an exact shape, which is one method with fixed parameter types and a fixed result type.

Why an interface? The loop must call the rule, so the compiler needs to know the method's name, parameters and result. An interface states exactly that. Because the interface has only one method without a body, a short piece of code with an arrow can only mean "the body of that method".

One loop, two rules

interface Check {
    boolean accept(int grams);
}
public class Main {
    static int tally(int[] load, Check rule) {
        int hits = 0;
        for (int g : load) {
            if (rule.accept(g)) hits++;
        }
        return hits;
    }
    public static void main(String[] args) {
        int[] load = {250, 900, 40, 610};
        System.out.println(tally(load, g -> g > 500));
        System.out.println(tally(load, g -> g < 100));
    }
}
Functional interface

A functional interface has exactly one abstract method. It may also have default and static methods, because those already have bodies. A lambda can be used wherever such an interface is expected.

Ways to write a lambda for an interface method

FormWhen it is allowed
g -> g > 500one parameter, one expression; its value is returned
(a, b) -> a + btwo or more parameters need brackets
() -> 7no parameters need empty brackets
g -> { int h = g * 2; return h > 9; }a block body; a value is returned only by return
String::lengtha method reference: an existing method used as the body

Worked example: When the body runs

Problem.

What does this program print, and in which order?

interface Greeter {
    String greet(String name);
}
public class Main {
    public static void main(String[] args) {
        Greeter g = name -> {
            System.out.println("building");
            return "hi " + name;
        };
        System.out.println("ready");
        System.out.println(g.greet("Ira"));
    }
}

What is asked.

The three printed lines.

Idea.

Writing a lambda stores it. Only a call of the interface method runs it.

  1. The assignment to g creates the function and runs none of its body.
  2. The next statement prints ready.
  3. g.greet("Ira") now runs the body, which prints building.
  4. The body returns hi Ira, and the outer println prints it.

Answer.

ready, building, hi Ira

Common mistake.

Printing building first because the lambda is written first.

What if

The Check program prints 2 and then 1.

  • Check gets a second method without a body: boolean reject(int grams); What happens to the program?
    It no longer compiles.. With two abstract methods the interface is not functional, so neither arrow expression has a single method to fill.
  • The second method is a default one: default int limit() { return 0; } Does anything change?
    It still compiles and prints 2 then 1.. A default method already has a body, so there is still exactly one abstract method.
  • Check becomes abstract class Check { abstract boolean accept(int grams); } Can the lambdas still be passed in?
    No, it does not compile.. A lambda can only fill an interface. A class is never a target, even with one abstract method.

You rarely need to declare the interface yourself. The package java.util.function already has the common shapes. Streams use them, so learn what goes in and what comes out.

Library shapes you will meet

InterfaceIts one methodIn, then outUsed by
Predicate<T>testa T, then booleanfilter, takeWhile, dropWhile
Function<T,R>applya T, then an Rmap
Consumer<T>accepta T, then nothingforEach
Supplier<T>getnothing, then a Tcode that makes values
UnaryOperator<T>applya T, then a Titerate

Worked example: Four shapes in one program

Problem.

What are the three lines?

import java.util.function.*;
public class Main {
    public static void main(String[] args) {
        Supplier<String> pick = () -> "mint";
        Predicate<String> isLong = s -> s.length() > 4;
        Function<String, Integer> size = String::length;
        Consumer<String> shout = s -> System.out.println(s + "!");
        String herb = pick.get();
        System.out.println(isLong.test(herb));
        System.out.println(size.apply(herb) * 10);
        shout.accept(herb);
    }
}

What is asked.

The printed lines.

Idea.

For each variable ask what goes in and what comes out, then follow the calls.

  1. pick.get() takes nothing and gives mint, so herb is mint.
  2. isLong.test(herb) asks whether 4 is greater than 4: false.
  3. size.apply(herb) calls herb.length() and gets 4; times 10 is 40.
  4. shout.accept(herb) returns nothing; it prints mint! itself.

Answer.

false, 40, mint!

Common mistake.

Writing System.out.println(shout.accept(herb)). A Consumer returns nothing, so that line does not compile.

Expression body or block body

Expression

The value is returned automatically. No braces, no return.

n -> n * n

Block

Statements inside braces. A value needs return and a semicolon.

n -> { return n * n; }

The difference. The braces.

Braces switch off the automatic return: n -> { n * n; } does not compile.

When this breaks

"A lambda gets its type from its place" fails when the place gives no type. var f = n -> n + 1; does not compile, because var asks the right side for a type and the lambda has none. Object o = n -> n + 1; fails too: Object is not a functional interface.

2. Pipelines and laziness

A pipeline is described first and runs later, element by element.

when the steps of a stream run and in what order

A shop packs bags. Rule: pick only even-numbered bags, relabel each one, and stop after two parcels. With loops you would take one bag, check it, relabel it, ship it, and only then pick up the next. How many bags would you touch?

A stream works like that worker, not like three separate workers who each finish the whole pile. The analogy stops in one place: the stream worker does not move at all until someone at the end asks for a parcel.

Why lazy? If every step processed the whole list first, then "stop after two" would come too late, and an endless source could never be used. So middle steps only record what to do. The final step pulls one element through the whole chain, then asks for the next.

Two kinds of step

KindExamplesReturnsRuns the pipeline?
intermediatefilter, map, skip, limit, takeWhile, dropWhilea new streamno
terminalforEach, counta value, or nothing (void)yes

The packing line

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> bags = List.of(7, 4, 9, 6, 2, 8);
        bags.stream()
            .filter(n -> {
                System.out.println("test " + n);
                return n % 2 == 0;
            })
            .map(n -> n * 10)
            .limit(2)
            .forEach(n -> System.out.println("packed " + n));
        System.out.println("done");
    }
}

One element at a time

  1. The pipeline is built. Only forEach, the last step, makes elements start to move.
  2. filter asks about 7 and prints its test line first.
  3. 7 is odd, so it is dropped here. map never sees it.
  4. The next element is pulled only now. filter tests 4.
  5. 4 is even, so it travels on to map.
  6. map replaced 4 with 40. limit lets it through and has one place left.
  7. 40 reaches forEach before 9 has even been looked at.
  8. filter tests 9.
  9. 9 is odd and is dropped.
  10. filter tests 6.
  11. 6 passes to map.
  12. limit lets 60 through. Its two places are now used.
  13. 60 is printed.
  14. limit is full, so nothing more is pulled. 2 and 8 are never tested. Then main prints done.

Worked example: A plan with no order given

Problem.

What does this print, line by line?

import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        Stream<String> plan = Stream.of("oat", "rye")
            .map(g -> {
                System.out.println("milling " + g);
                return g + " flour";
            });
        System.out.println("plan made");
        plan.forEach(System.out::println);
    }
}

What is asked.

All printed lines in order.

Idea.

Find the line that holds the terminal operation. Nothing in the pipeline prints before it.

  1. The map call stores the lambda and returns a new stream. Nothing is milled.
  2. plan made is printed.
  3. forEach pulls oat: map prints milling oat, then forEach prints oat flour.
  4. Only then is rye pulled: milling rye, then rye flour.

Answer.

plan made, milling oat, oat flour, milling rye, rye flour

Common mistake.

Printing both milling lines together. Each element finishes its whole journey first.

What if

The packing line prints test lines for 7, 4, 9 and 6, two packed lines (40 and 60) and done.

  • The line .limit(2) is removed. How many test lines and packed lines appear now?
    It prints six test lines and four packed lines: 40, 60, 20 and 80.. Nothing stops the flow early, so every bag is tested and each even one is packed as soon as it passes.
  • .limit(2) moves above filter. What is packed?
    It prints test 7, test 4, packed 40 and done.. Only the first two source elements are ever allowed into filter, and one of them is odd.
  • The forEach step is deleted, so the statement ends after limit(2). What is printed?
    It prints only done.. With no terminal operation, the test lambda is never called.

Two more middle steps control how many elements pass. skip(k) throws away the first k elements that reach it. limit(k) lets at most k through and then stops the flow. Both count what reaches them, so their place in the chain matters.

Worked example: skip after a filter

Problem.

What are the printed lines?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> laps = List.of(52, 71, 48, 66, 59, 80);
        laps.stream()
            .filter(t -> t < 70)
            .skip(2)
            .map(t -> "lap " + t)
            .forEach(System.out::println);
    }
}

What is asked.

The output.

Idea.

Write one row per step; skip counts the elements arriving from filter, not from the list.

  1. filter keeps the times under 70: 52, 48, 66, 59.
  2. skip(2) removes the first two that reach it, 52 and 48.
  3. map turns the other two into lap 66 and lap 59.
  4. forEach prints them.

Answer.

lap 66, lap 59

Common mistake.

Skipping 52 and 71, the first two in the list. filter had already removed 71, so 48 is the second to arrive.

The order of skip and limit

skip then limit

On p q r s t: drop one, then keep two. Prints qr.

.skip(1)
.limit(2)

limit then skip

On p q r s t: keep two, then drop one. Prints q.

.limit(2)
.skip(1)

The difference. Which of the two comes first.

Each step works only on what the previous step hands over.

Both orders, run

import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        Stream.of("p", "q", "r", "s", "t")
              .skip(1)
              .limit(2)
              .forEach(System.out::print);
        System.out.println();
        Stream.of("p", "q", "r", "s", "t")
              .limit(2)
              .skip(1)
              .forEach(System.out::print);
        System.out.println();
    }
}

Worked example: Asking twice

Problem.

What happens when this program runs?

import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        Stream<String> keys = Stream.of("do", "re", "mi");
        long total = keys.count();
        System.out.println(total);
        keys.forEach(System.out::println);
    }
}

What is asked.

The output, and how the program ends.

Idea.

count is a terminal operation, so it uses the stream up.

  1. count() runs the stream and returns 3 as a long, so 3 is printed.
  2. keys still names the same stream object, which has been used.
  3. keys.forEach(...) compiles, because the type is right, but throws IllegalStateException when it runs.

Answer.

3, then an IllegalStateException

Common mistake.

Calling it a compilation error. The compiler cannot tell that the stream was used.

When this breaks

"The terminal step pushes every element through every middle step" is not promised for count. If the number of elements is already known from the source, the API lets count skip the middle steps. Never rely on printing inside a pipeline that ends in count.

A silent count

import java.util.*;
public class Main {
    public static void main(String[] args) {
        long n = List.of("x", "y", "z").stream()
            .peek(s -> System.out.println("saw " + s))
            .count();
        System.out.println(n);
    }
}

3. filter versus map

Two steps look alike and do completely different jobs.

which step keeps elements and which step replaces them

A van carries parcels. Among the parcels over 5 kg, you want the city names longer than four letters. One step must decide which parcels stay. Another must turn a parcel into something else, its city name. These are two different jobs.

filter is a guard at a door: each visitor either enters unchanged or is turned away. map is a currency counter: every note handed in comes back as something else, and nobody is turned away. The analogy stops here: neither one touches the original list.

Why the type matters. The compiler checks each lambda against the values arriving at that step. filter hands on the type it received. map hands on the type its lambda returns. So one wrong map turns parcels into booleans, and a later p.city has nothing to look at.

filtermap
Lambda shapePredicate: element in, boolean outFunction: element in, any value out
Number of elementssame or fewerexactly the same
Valuesunchangedreplaced
Type after the stepunchangedthe lambda's result type

Guard, change, guard

import java.util.*;
class Parcel {
    String city;
    int kg;
    Parcel(String city, int kg) {
        this.city = city;
        this.kg = kg;
    }
}
public class Main {
    public static void main(String[] args) {
        List<Parcel> van = List.of(new Parcel("Pune", 4), new Parcel("Agra", 11),
                new Parcel("Surat", 7), new Parcel("Kochi", 15));
        van.stream()
           .filter(p -> p.kg > 5)
           .map(p -> p.city)
           .filter(c -> c.length() > 4)
           .forEach(System.out::println);
    }
}

Three readings, ready to step through

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> readings = List.of(12, 30, 45);
        readings.stream()
                .filter(n -> n > 20)
                .map(n -> n + "C")
                .forEach(System.out::println);
    }
}

filter keeps, map replaces

  1. Three readings are queued. filter can only keep or drop; map can only replace.
  2. filter asks: is 12 over 20?
  3. No. The element is gone, and its value was never changed.
  4. filter asks about 30.
  5. Yes. The same 30 goes on, unchanged.
  6. map hands on a new value, the text 30C, which is printed.
  7. filter asks about 45.
  8. 45 passes, still a number.
  9. The number became text at map. Two lines come out of three elements.

Worked example: A map that asks a question

Problem.

What does this print?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> temps = List.of(18, 31, 25);
        temps.stream()
             .map(t -> t > 24)
             .forEach(System.out::println);
    }
}

What is asked.

The three lines.

Idea.

map replaces each element with the answer to the question.

  1. 18 > 24 is false, so 18 is replaced by false.
  2. 31 > 24 is true, and 25 > 24 is true.
  3. All three booleans reach forEach; nothing was removed.

Answer.

false, true, true

Common mistake.

Printing 31 and 25. That would need filter.

What if

The van program keeps parcels over 5 kg, maps them to cities, keeps names longer than four letters, and prints Surat and Kochi.

  • The map line moves above the first filter. Does it still compile?
    It does not compile.. The weight test now receives a String, and a String has no field kg.
  • The first guard becomes p.kg > 5 || p.city.length() > 4, and the second filter is removed. What prints?
    It prints Agra, Surat, Kochi.. With "or" one true side is enough, so Agra now gets through. The chain of two guards had meant that both rules must hold.
  • The second filter becomes map with the same lambda. What prints?
    It prints false, true, true.. The program still compiles, because nothing later needs a String. Each city is replaced by the answer to the question.

Worked example: The same two steps, two orders

Problem.

What are the two lines?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> stock = List.of(6, 14, 3, 21);
        stock.stream()
             .map(n -> n * 2)
             .filter(n -> n > 20)
             .forEach(n -> System.out.print("[" + n + "]"));
        System.out.println();
        stock.stream()
             .filter(n -> n > 20)
             .map(n -> n * 2)
             .forEach(n -> System.out.print("[" + n + "]"));
        System.out.println();
    }
}

What is asked.

Both printed lines.

Idea.

In the first pipeline the test sees doubled numbers; in the second it sees the originals.

  1. Pipeline 1: map gives 12, 28, 6, 42. The test over 20 keeps 28 and 42.
  2. Pipeline 2: the test over 20 sees 6, 14, 3, 21 and keeps only 21.
  3. map then doubles it to 42.

Answer.

[28][42] and then [42]

Common mistake.

Testing the original numbers in the first pipeline. map has already replaced them.

One word, another meaning

filter

Keeps the elements for which the lambda is true.

.filter(t -> t > 24)
// on 18, 31, 25: 31, 25

map

Replaces each element with the lambda's result.

.map(t -> t > 24)
// on 18, 31, 25: false, true, true

The difference. The name of the step.

A boolean lambda fits both, so read the step name first.

When this breaks

"Swapping a filter for a map is a compilation error" is false. map with a boolean lambda compiles on its own. The error appears only if a later step uses something that a Boolean does not have. If the later step just prints the element, the program runs and prints true and false.

4. iterate and size control

A stream can be built from a starting value and a rule for the next one.

sources that can run for ever, and the steps that cut them short

You want the first three even numbers in the series 2, 7, 12, 17, and so on, adding 5 each time. The series has no end. How can a program work with it and still finish?

Think of a ticket machine. It does not print all tickets in advance; it prints the next one when someone pulls. iterate is such a machine. The analogy stops at one point: this machine never runs out of paper, so you must decide when to stop pulling.

Why it can finish. Because streams are lazy, a value is made only when the pipeline asks for it. A step such as limit(3) stops asking after three elements have passed it, so the endless part is simply never made.

Two forms of iterate

Stream.iterate(seed, f) gives seed, f(seed), f(f(seed)) and so on without end. Stream.iterate(seed, hasNext, f) gives the same values while hasNext is true, like the header of a for loop, and then ends.

First three even values

import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        Stream.iterate(2, n -> n + 5)
              .filter(n -> n % 2 == 0)
              .limit(3)
              .forEach(System.out::println);
    }
}

An endless source, a finite answer

  1. iterate can make values for ever. It makes one only when the pipeline asks.
  2. The seed 2 is the first element.
  3. 2 passes, uses one place and is printed.
  4. 7 is odd. It is dropped and does not use a place.
  5. 12 is next.
  6. 12 is printed.
  7. 17 is odd and dropped.
  8. 22 is next.
  9. The third survivor is printed. limit is full, so the endless source is asked for nothing more.

Worked example: A source that ends itself

Problem.

What are the two printed lines?

import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        Stream.iterate(1, n -> n < 40, n -> n * 3)
              .forEach(n -> System.out.print(n + ";"));
        System.out.println();
        System.out.println(Stream.iterate(10, n -> n > 0, n -> n - 4).count());
    }
}

What is asked.

Both lines.

Idea.

Read the three arguments like a for loop: start, keep going while, next.

  1. First stream: 1, 3, 9, 27 satisfy n < 40. The next value, 81, fails, so the stream ends.
  2. Second stream: 10, 6, 2 satisfy n > 0. The next value, -2, fails.
  3. count returns 3.

Answer.

1;3;9;27; and then 3

Common mistake.

Including 81, the first value that fails the condition.

What if

iterate(2, n -> n + 5), then the even test, then limit(3), prints 2, 12, 22.

  • limit(3) moves above filter. What prints now?
    It prints 2 and 12.. limit now counts source values: 2, 7, 12. Only two of those are even.
  • The rule becomes n -> n + 4. Which three values print?
    It prints 2, 6, 10.. Every value is now even, so the first three source values are also the first three survivors.
  • The rule becomes n -> n + 2 and the test becomes n % 2 != 0. What happens?
    It prints nothing and never ends.. Adding 2 to an even number gives an even number, even after overflow, so the test never succeeds and limit(3) never fills.

Worked example: The odd test and negative numbers

Problem.

What are the two lines?

import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        Stream.iterate(7, n -> n - 3)
              .limit(5)
              .filter(n -> n % 2 == 1)
              .forEach(n -> System.out.print(n + "|"));
        System.out.println();
        Stream.iterate(7, n -> n - 3)
              .limit(5)
              .filter(n -> n % 2 != 0)
              .forEach(n -> System.out.print(n + "|"));
        System.out.println();
    }
}

What is asked.

Both lines.

Idea.

limit(5) fixes the five candidates first. Then compare the remainders, which are negative for negative odd numbers.

  1. The five candidates are 7, 4, 1, -2, -5.
  2. % keeps the sign of the left number: 7 % 2 is 1, 1 % 2 is 1, -5 % 2 is -1.
  3. The test == 1 therefore keeps only 7 and 1.
  4. The test != 0 keeps 7, 1 and -5.

Answer.

7|1| and then 7|1|-5|

Common mistake.

Assuming n % 2 == 1 means "odd". It misses negative odd numbers.

Where limit stands

limit, then filter

At most three candidates are looked at.

.limit(3)
.filter(n -> n % 2 == 0)

filter, then limit

Candidates are looked at until three have survived.

.filter(n -> n % 2 == 0)
.limit(3)

The difference. The order of the two lines.

limit before the test bounds the work; after it, limit bounds the results, and can run for ever if too few survive.

When this breaks

"The values keep growing, so after a while none of them can pass n < 2_000_002" is false. An int that goes past 2147483647 wraps round to a large negative number, and negative numbers pass the test again. A filter never ends the stream; it only says no to single values.

Overflow brings values back

import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        Stream.iterate(1, n -> n + 1_000_000)
              .filter(n -> n < 2_000_002)
              .limit(4)
              .forEach(System.out::println);
    }
}

5. takeWhile, dropWhile and filter

The same test can mean three things, depending on the step that holds it.

three steps that use a true-or-false test in different ways

A row of numbered boxes arrives: 4, 6, 9, 2, 11, 8. The test is "even". You could keep every even box. You could keep boxes only until the first odd one. Or you could throw boxes away until the first odd one, then keep the rest. Three jobs, one test.

takeWhile is a doorman who shuts the door at the first wrong guest and goes home. dropWhile is a doorman who turns guests away until the first one who breaks the pattern, then leaves the door open for everybody. The analogy stops here: neither doorman reorders anyone.

Why only once? These steps speak about the front of the stream. After the front has ended, there is nothing left to ask: takeWhile is finished, and dropWhile has nothing more to remove.

filtertakeWhiledropWhile
Elements testedallup to the first failureup to the first failure
The first failing elementdroppeddropped, and the flow stopskept
Later passing elementskeptlostkept
On 4, 6, 9, 2, 11, 8 (even)4, 6, 2, 84, 69, 2, 11, 8

One test, three steps

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> row = List.of(4, 6, 9, 2, 11, 8);
        System.out.print("filter:");
        row.stream().filter(n -> n % 2 == 0).forEach(n -> System.out.print(" " + n));
        System.out.println();
        System.out.print("takeWhile:");
        row.stream().takeWhile(n -> n % 2 == 0).forEach(n -> System.out.print(" " + n));
        System.out.println();
        System.out.print("dropWhile:");
        row.stream().dropWhile(n -> n % 2 == 0).forEach(n -> System.out.print(" " + n));
        System.out.println();
    }
}

takeWhile: a gate that closes once

  1. takeWhile starts with its gate open.
  2. 4 is tested: even.
  3. 4 is printed.
  4. 6 is tested: even.
  5. 6 is printed.
  6. 9 is the first failure. It is dropped and the gate closes for good. 2 and 8 are even, but are never pulled.

dropWhile: a gate that opens once

  1. dropWhile starts by throwing elements away.
  2. 4 is even, so it is dropped.
  3. 6 is even, so it is dropped.
  4. 9 is the first failure. The dropping stops for good.
  5. 9 itself is kept and printed.
  6. 2 is even, but nothing tests it any more.
  7. 11 goes straight through.
  8. 8 goes straight through too.

Worked example: Two gates in a chain

Problem.

What does this print?

import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        Stream.of(41, 38, 29, 44, 27)
              .dropWhile(t -> t > 35)
              .takeWhile(t -> t < 45)
              .forEach(t -> System.out.print(t + "C "));
        System.out.println();
    }
}

What is asked.

The printed line.

Idea.

Run the front gate first; the second step sees only what leaves the first.

  1. dropWhile over 35: 41 and 38 are dropped. 29 fails, so 29 and everything after it pass: 29, 44, 27.
  2. takeWhile under 45 sees 29, 44, 27. All three pass, so the gate never closes.
  3. The numbers are printed with C.

Answer.

29C 44C 27C

Common mistake.

Dropping 44 because it is over 35. dropWhile had already stopped testing.

What if

On 4, 6, 9, 2, 11, 8 with the test "even", takeWhile gives 4 6 and dropWhile gives 9 2 11 8.

  • The data starts with 9: the row is 9, 4, 6. What do the two steps give?
    takeWhile prints nothing; dropWhile prints all of 9 4 6.. The very first element fails, so the taking ends at once and the dropping never starts.
  • The row is 4, 6, 2: every element is even. What do the two steps give?
    takeWhile prints 4 6 2; dropWhile prints nothing.. No element ever fails, so everything is taken, or everything is dropped.
  • The row is sorted so that all even numbers come first: 2, 4, 6, 8, 9, 11. How does takeWhile compare with filter now?
    Both print 2 4 6 8.. When no passing element comes after a failing one, stopping early loses nothing.

Worked example: An endless source with a gate

Problem.

What does this program print?

import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        long small = Stream.iterate(1, n -> n * 2)
                           .takeWhile(n -> n < 50)
                           .count();
        System.out.println(small);
        Stream.iterate(1, n -> n * 2)
              .dropWhile(n -> n < 50)
              .limit(3)
              .forEach(System.out::println);
    }
}

What is asked.

A count, then the later lines.

Idea.

On a growing series, takeWhile gives a finite front part. dropWhile removes that part and leaves an endless rest, so a limit is needed.

  1. The source is 1, 2, 4, 8, 16, 32, 64, 128 and so on.
  2. takeWhile(n < 50) passes 1 to 32 and stops at 64: six elements, so 6.
  3. dropWhile(n < 50) removes the same six and passes 64 onwards.
  4. limit(3) stops after 64, 128 and 256.

Answer.

6, 64, 128, 256

Common mistake.

Counting 64 in the first answer.

Stop or skip

takeWhile on an endless stream

Ends at the first failure, so count returns.

.takeWhile(n -> n < 50)
.count()

filter on an endless stream

Only rejects single values. The source is never told to stop, so count never returns.

.filter(n -> n < 50)
.count()

The difference. The name of the step.

Only takeWhile tells the source to stop.

When this breaks

"dropWhile makes an endless stream finite, like takeWhile" is false. It removes only the front. What remains of an endless stream is still endless, so count after it never returns.

6. Equivalent pipelines

Different code can print identical text, and similar code can print different text.

how to decide whether two pieces of stream code do the same thing

Two teammates print the same three herb names in capitals. One starts from an array, the other from listed values, and one writes String::toUpperCase. Do they print the same thing? You must be able to answer without running them.

Think of two recipes for the same dish. The ingredients may come from different shops and the steps may be worded differently. What counts is the plate. The analogy stops here: for code, "nearly the same plate" is a different answer.

Why a checklist works. Output depends on four things only: which values leave the last middle step, their order, how the final step writes them, and whether the program gets to the end. Compare those four and nothing else.

Sources that can stand for each other

Written asElements
Stream.of(a, b, c)the listed values, in order
Stream.of(arr) or Arrays.stream(arr)the array's values (an array of objects)
list.stream()the list's values, in list order
Stream.iterate(s, f).limit(k)the first k values of the series
Stream.iterate(s, test, f)values of the series while the test holds

Three ways, one output

import java.util.*;
import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        String[] herbs = {"basil", "dill", "sage"};
        Arrays.stream(herbs)
              .map(String::toUpperCase)
              .forEach(System.out::println);
        Stream.of(herbs)
              .map(h -> h.toUpperCase())
              .forEach(h -> System.out.println(h));
        List.of("basil", "dill", "sage").stream()
              .map(h -> h.toUpperCase())
              .forEach(System.out::println);
    }
}

Worked example: Four spellings of one series

Problem.

What do the four lines show?

import java.util.stream.*;
public class Main {
    static void show(Stream<Integer> s) {
        s.forEach(n -> System.out.print(n + " "));
        System.out.println();
    }
    public static void main(String[] args) {
        show(Stream.of(3, 6, 9, 12));
        show(Stream.iterate(3, n -> n + 3).limit(4));
        show(Stream.iterate(3, n -> n <= 12, n -> n + 3));
        show(Stream.iterate(1, n -> n + 1).map(n -> n * 3).takeWhile(n -> n <= 12));
    }
}

What is asked.

Each printed line.

Idea.

List the elements that reach show for every call.

  1. Listed values: 3, 6, 9, 12.
  2. iterate then limit(4): the first four values, 3, 6, 9, 12.
  3. The three-argument form keeps values up to and including 12.
  4. Counting from 1, multiplied by 3, taken while at most 12: again 3, 6, 9, 12.

Answer.

The same line four times: 3 6 9 12

Common mistake.

Putting limit or takeWhile before map without changing the number in the test.

What if

iterate(1, n -> n + 1).map(n -> n * 3).takeWhile(n -> n <= 12) gives 3, 6, 9, 12.

  • takeWhile moves above map, with the same lambda. What comes out?
    It gives 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36.. The test now sees the unmultiplied values 1 to 12, so twelve elements pass.
  • takeWhile becomes filter. Is the output still the same, and does it end?
    It prints the same four values first but never ends.. filter cannot stop the source, so the program is not equivalent.
  • The test becomes n < 12. What comes out?
    It gives 3, 6, 9.. 12 now fails, so the gate closes before it.

Worked example: Equal by luck

Problem.

The test is n < 5. Compare filter with takeWhile on two orders of the same numbers.

import java.util.stream.*;
public class Main {
    static void show(Stream<Integer> s) {
        s.forEach(n -> System.out.print(n + " "));
        System.out.println();
    }
    public static void main(String[] args) {
        show(Stream.of(2, 4, 7, 9).filter(n -> n < 5));
        show(Stream.of(2, 4, 7, 9).takeWhile(n -> n < 5));
        show(Stream.of(7, 2, 9, 4).filter(n -> n < 5));
        show(Stream.of(7, 2, 9, 4).takeWhile(n -> n < 5));
    }
}

What is asked.

The four printed lines.

Idea.

On the first order all passing values stand at the front; on the second they do not.

  1. On 2, 4, 7, 9 both steps give 2, 4.
  2. On 7, 2, 9, 4, filter gives 2, 4.
  3. takeWhile fails on the first value 7 and gives an empty line.

Answer.

2 4, 2 4, 2 4, and an empty line

Common mistake.

Declaring two steps equivalent after checking friendly data only.

print or println

println

Each element ends its own line.

.forEach(n -> System.out.println(n))

print with a space

All elements stay on one line.

.forEach(n -> System.out.print(n + " "))

The difference. The method that writes each element.

Equal values are not enough: the layout of the text must match too.

When this breaks

"System.out::println can replace any printing lambda" is false. The method reference prints exactly the element. A lambda such as n -> System.out.println(n + 1) prints something computed from it, so the reference would give different text unless a map does that computation first.

Practise this topic →

Weeks covering this topic

Other Java topics