Lazy pipelines built from lambdas.
Open the interactive lessons →Streams and Functional Interfaces past questions
Contents
- Lambdas and functional interfaces
- Pipelines and laziness
- filter versus map
- iterate and size control
- takeWhile, dropWhile and filter
- 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));
}
}
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
| Form | When it is allowed |
|---|---|
g -> g > 500 | one parameter, one expression; its value is returned |
(a, b) -> a + b | two or more parameters need brackets |
() -> 7 | no parameters need empty brackets |
g -> { int h = g * 2; return h > 9; } | a block body; a value is returned only by return |
String::length | a 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.
- The assignment to
gcreates the function and runs none of its body. - The next statement prints
ready. g.greet("Ira")now runs the body, which printsbuilding.- The body returns
hi Ira, and the outerprintlnprints it.
Answer.
ready, building, hi Ira
Common mistake.
Printing building first because the lambda is written first.
The Check program prints 2 and then 1.
Checkgets 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
defaultone:default int limit() { return 0; }Does anything change?
It still compiles and prints2then1.. Adefaultmethod already has a body, so there is still exactly one abstract method. Checkbecomesabstract 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
| Interface | Its one method | In, then out | Used by |
|---|---|---|---|
Predicate<T> | test | a T, then boolean | filter, takeWhile, dropWhile |
Function<T,R> | apply | a T, then an R | map |
Consumer<T> | accept | a T, then nothing | forEach |
Supplier<T> | get | nothing, then a T | code that makes values |
UnaryOperator<T> | apply | a T, then a T | iterate |
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.
pick.get()takes nothing and givesmint, soherbismint.isLong.test(herb)asks whether 4 is greater than 4:false.size.apply(herb)callsherb.length()and gets 4; times 10 is40.shout.accept(herb)returns nothing; it printsmint!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 * nBlock
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.
"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
| Kind | Examples | Returns | Runs the pipeline? |
|---|---|---|---|
| intermediate | filter, map, skip, limit, takeWhile, dropWhile | a new stream | no |
| terminal | forEach, count | a 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
- The pipeline is built. Only
forEach, the last step, makes elements start to move. filterasks about7and prints its test line first.7is odd, so it is dropped here.mapnever sees it.- The next element is pulled only now.
filtertests4. 4is even, so it travels on tomap.mapreplaced4with40.limitlets it through and has one place left.40reachesforEachbefore9has even been looked at.filtertests9.9is odd and is dropped.filtertests6.6passes tomap.limitlets60through. Its two places are now used.60is printed.limitis full, so nothing more is pulled.2and8are never tested. Thenmainprintsdone.
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.
- The
mapcall stores the lambda and returns a new stream. Nothing is milled. plan madeis printed.forEachpullsoat:mapprintsmilling oat, thenforEachprintsoat flour.- Only then is
ryepulled:milling rye, thenrye 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.
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 abovefilter. What is packed?
It printstest 7,test 4,packed 40anddone.. Only the first two source elements are ever allowed intofilter, and one of them is odd.- The
forEachstep is deleted, so the statement ends afterlimit(2). What is printed?
It prints onlydone.. 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.
filterkeeps the times under 70: 52, 48, 66, 59.skip(2)removes the first two that reach it, 52 and 48.mapturns the other two intolap 66andlap 59.forEachprints 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.
count()runs the stream and returns 3 as along, so3is printed.keysstill names the same stream object, which has been used.keys.forEach(...)compiles, because the type is right, but throwsIllegalStateExceptionwhen it runs.
Answer.
3, then an IllegalStateException
Common mistake.
Calling it a compilation error. The compiler cannot tell that the stream was used.
"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.
filter | map | |
|---|---|---|
| Lambda shape | Predicate: element in, boolean out | Function: element in, any value out |
| Number of elements | same or fewer | exactly the same |
| Values | unchanged | replaced |
| Type after the step | unchanged | the 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
- Three readings are queued.
filtercan only keep or drop;mapcan only replace. filterasks: is12over 20?- No. The element is gone, and its value was never changed.
filterasks about30.- Yes. The same
30goes on, unchanged. maphands on a new value, the text30C, which is printed.filterasks about45.45passes, still a number.- 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.
18 > 24isfalse, so18is replaced byfalse.31 > 24istrue, and25 > 24istrue.- All three booleans reach
forEach; nothing was removed.
Answer.
false, true, true
Common mistake.
Printing 31 and 25. That would need filter.
The van program keeps parcels over 5 kg, maps them to cities, keeps names longer than four letters, and prints Surat and Kochi.
- The
mapline moves above the firstfilter. Does it still compile?
It does not compile.. The weight test now receives aString, and aStringhas no fieldkg. - The first guard becomes
p.kg > 5 || p.city.length() > 4, and the secondfilteris removed. What prints?
It printsAgra,Surat,Kochi.. With "or" one true side is enough, soAgranow gets through. The chain of two guards had meant that both rules must hold. - The second
filterbecomesmapwith the same lambda. What prints?
It printsfalse,true,true.. The program still compiles, because nothing later needs aString. 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.
- Pipeline 1:
mapgives 12, 28, 6, 42. The test over 20 keeps 28 and 42. - Pipeline 2: the test over 20 sees 6, 14, 3, 21 and keeps only 21.
mapthen 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, 25map
Replaces each element with the lambda's result.
.map(t -> t > 24)
// on 18, 31, 25: false, true, trueThe difference. The name of the step.
A boolean lambda fits both, so read the step name first.
"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.
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
iteratecan make values for ever. It makes one only when the pipeline asks.- The seed
2is the first element. 2passes, uses one place and is printed.7is odd. It is dropped and does not use a place.12is next.12is printed.17is odd and dropped.22is next.- The third survivor is printed.
limitis 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.
- First stream: 1, 3, 9, 27 satisfy
n < 40. The next value, 81, fails, so the stream ends. - Second stream: 10, 6, 2 satisfy
n > 0. The next value, -2, fails. countreturns 3.
Answer.
1;3;9;27; and then 3
Common mistake.
Including 81, the first value that fails the condition.
iterate(2, n -> n + 5), then the even test, then limit(3), prints 2, 12, 22.
limit(3)moves abovefilter. What prints now?
It prints2and12..limitnow counts source values: 2, 7, 12. Only two of those are even.- The rule becomes
n -> n + 4. Which three values print?
It prints2,6,10.. Every value is now even, so the first three source values are also the first three survivors. - The rule becomes
n -> n + 2and the test becomesn % 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 andlimit(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.
- The five candidates are 7, 4, 1, -2, -5.
%keeps the sign of the left number:7 % 2is 1,1 % 2is 1,-5 % 2is -1.- The test
== 1therefore keeps only 7 and 1. - The test
!= 0keeps 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.
"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.
filter | takeWhile | dropWhile | |
|---|---|---|---|
| Elements tested | all | up to the first failure | up to the first failure |
| The first failing element | dropped | dropped, and the flow stops | kept |
| Later passing elements | kept | lost | kept |
| On 4, 6, 9, 2, 11, 8 (even) | 4, 6, 2, 8 | 4, 6 | 9, 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
takeWhilestarts with its gate open.4is tested: even.4is printed.6is tested: even.6is printed.9is the first failure. It is dropped and the gate closes for good.2and8are even, but are never pulled.
dropWhile: a gate that opens once
dropWhilestarts by throwing elements away.4is even, so it is dropped.6is even, so it is dropped.9is the first failure. The dropping stops for good.9itself is kept and printed.2is even, but nothing tests it any more.11goes straight through.8goes 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.
dropWhileover 35: 41 and 38 are dropped. 29 fails, so 29 and everything after it pass: 29, 44, 27.takeWhileunder 45 sees 29, 44, 27. All three pass, so the gate never closes.- The numbers are printed with
C.
Answer.
29C 44C 27C
Common mistake.
Dropping 44 because it is over 35. dropWhile had already stopped testing.
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?
takeWhileprints nothing;dropWhileprints 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?
takeWhileprints 4 6 2;dropWhileprints 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
takeWhilecompare withfilternow?
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.
- The source is 1, 2, 4, 8, 16, 32, 64, 128 and so on.
takeWhile(n < 50)passes 1 to 32 and stops at 64: six elements, so6.dropWhile(n < 50)removes the same six and passes 64 onwards.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.
"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 as | Elements |
|---|---|
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.
- Listed values: 3, 6, 9, 12.
iteratethenlimit(4): the first four values, 3, 6, 9, 12.- The three-argument form keeps values up to and including 12.
- 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.
iterate(1, n -> n + 1).map(n -> n * 3).takeWhile(n -> n <= 12) gives 3, 6, 9, 12.
takeWhilemoves abovemap, 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.takeWhilebecomesfilter. Is the output still the same, and does it end?
It prints the same four values first but never ends..filtercannot 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.
- On 2, 4, 7, 9 both steps give 2, 4.
- On 7, 2, 9, 4,
filtergives 2, 4. takeWhilefails 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.
"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.