Lambdas and Streams
Applied class for 2026-05-21-correct-programming (Week 12). Extends java-lambdas-and-streams (Week 11) with practice reading λ-function traces and standard functional interfaces (Function, BiFunction, Predicate, Supplier, Consumer, BiConsumer, UnaryOperator).
On the HTML site, fill in each blank with your answer as a quoted string (e.g. "6", "Hello World"), then click Run Code to check it. Interactive checking needs a browser, so the blanks do not appear in the PDF; the collapsed Working callout under each task holds the answer either way.
§1 \(\lambda\)-functions
In Java, if an implementation of a functional interface is expected, it can be substituted with a \(\lambda\) (lambda) function. \(\lambda\)-functions take three forms — the general shape on top, a concrete instance boxed beneath it:
Figure 1: The three lambda-function forms, one per column: the general form on top and a boxed concrete example below it.
Lambdas are short-hand for an implementation of a functional interface — an interface with only one method. A motivating example:
interface GrabData<T> {
void takeThis(T data);
}
class LambdaExample {
public <T> void distributeData(List<T> data, GrabData<T> grabber) {
for (T element : data) {
grabber.takeThis(element);
}
}
}To supply a GrabData<T> you can take the traditional approach and write a named class:
class PrintData<T> implements GrabData<T> {
public void takeThis(T data) {
System.out.println(data);
}
}
...
List<String> words = List.of("alpha", "bravo", "charlie", "delta");
distributeData(words, new PrintData<>());The diamond matters: a bare new PrintData() is the raw type.
…or use a \(\lambda\)-function, which is the same implementation with the class, its name and the method signature deleted:
List<String> words = List.of("alpha", "bravo", "charlie", "delta");
distributeData(words, (data) -> {
System.out.println(data);
});This is much more concise, and encourages using functional interfaces throughout the code base.
The tasks below use the standard functional interfaces from java.util.function. Each has a single abstract method, and the Used in column lists the tasks that use it:
| Interface | Abstract method | Used in |
|---|---|---|
Function<T, R> |
R apply(T) |
Tasks 0, 2, 3, 6, 8, 9, 10, 13, 14 |
BiFunction<T, U, R> |
R apply(T, U) |
Tasks 5, 13 |
UnaryOperator<T> |
T apply(T) |
Tasks 7, 14 |
Predicate<T> |
boolean test(T) |
Task 4 |
Supplier<T> |
T get() |
Tasks 1, 12, 13 |
Consumer<T> |
void accept(T) |
Tasks 11, 12 |
BiConsumer<T, U> |
void accept(T, U) |
Task 12 |
Task 0. What is printed by:
Function<Integer, Integer> f = x -> 2 * x;
System.out.println(f.apply(3));6
Task 1. What is printed by:
Supplier<String> c = () -> "Hello World";
System.out.println(c.get());Hello World
Task 2. What is printed by:
int power = 3;
Function<Integer, Double> g = x -> Math.pow(x, power);
System.out.println(g.apply(5));125.0 (\(5^3\))
Task 3. What is printed by:
int power = 3;
Function<Integer, Double> g = x -> Math.pow(x, power);
power = 2;
System.out.println(g.apply(5));Does not compile — power is reassigned after the lambda captures it, so it is not effectively final, which lambdas require of any local variable they capture.
Task 4. What is printed by:
Predicate<Integer> p = x -> x % 2 == 0;
System.out.println(p.test(4));true
Task 5. What is printed by:
BiFunction<Integer, Integer, Integer> add = (x, y) -> x + y;
System.out.println(add.apply(3, 5));8
Task 6. What is printed by:
Function<String, Integer> strLength = String::length;
System.out.println(strLength.apply("Hello"));5 — String::length is a method reference, equivalent to s -> s.length().
Task 7. What is printed by:
UnaryOperator<Integer> square = x -> x * x;
System.out.println(square.apply(4));16
Task 8. What is printed by:
int base = 2;
Function<Integer, Double> exp = x -> Math.pow(base, x);
System.out.println(exp.apply(3));8.0 (\(2^3\))
Task 9. What is printed by:
Function<Integer, Integer> factorial = n -> {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
};
System.out.println(factorial.apply(4));24 (\(4! = 4 \times 3 \times 2 \times 1\))
Task 10. What is printed by:
Function<Integer, Integer> f1 = x -> x + 1;
Function<Integer, Integer> f2 = x -> x * 2;
Function<Integer, Integer> composed = f1.andThen(f2);
System.out.println(composed.apply(3));8 — andThen runs f1 first (3 + 1 = 4), then f2 on that result (4 * 2 = 8).
Task 11. What is printed by:
List<Integer> numbers = new ArrayList<>();
Consumer<Integer> addTo = (number) -> numbers.add(number);
addTo.accept(24);
addTo.accept(42);
System.out.println(numbers);{24, 42}
Task 12. What is printed by:
Supplier<StringBuilder> supplier = StringBuilder::new;
BiConsumer<StringBuilder, String> appender = StringBuilder::append;
Consumer<StringBuilder> printer = System.out::println;
StringBuilder sb = supplier.get();
appender.accept(sb, "cher");
appender.accept(sb, "ryp");
appender.accept(sb, "ick");
printer.accept(sb);cherrypick
Task 13. What code snippet replaces ??? so this prints 10?
BiFunction<Integer, Function<Integer, Integer>, Supplier<Integer>> g =
(i, f) -> ??? ;
System.out.println(g.apply(5, x -> x * 2).get());() -> f.apply(i) — g returns a Supplier<Integer>, a zero-argument lambda that, when later called via .get(), applies f to i (5 * 2 = 10).
Task 14. What is printed by:
Function<Integer, Integer> f = x -> x * 2;
UnaryOperator<Integer> g = x -> x + 1;
Function<Integer, Integer> h = f.andThen(g).andThen(f).andThen(g);
System.out.println(h.apply(3));15 — chained left to right: f(3)=6, g(6)=7, f(7)=14, g(14)=15.
How a chain of andThen runs
andThen reads left to right: a.andThen(b) means “run a, then feed its result into b”. Task 14’s four-link chain traced out:
Figure 2: Task 14’s chain h = f.andThen(g).andThen(f).andThen(g) evaluated at 3, with the value passed between each pair of stages. The stages apply left to right and the answer is 15.
The trap is reading f.andThen(g) as \(f \circ g\) — it is the other way round, \(g \circ f\). (Function also has a compose method that does go the other way, but none of these tasks use it.)
Task 10 is the same idea with one link: f1.andThen(f2) on 3 gives 3 + 1 = 4, then 4 * 2 = 8.
§2 Streams
In Java, most built-in collections can be converted to a stream for processing, and lambdas tend to be very useful in applying transformations to streams. See java.util.stream.
List results are written with set braces throughout — {2, 4, 6, 8}, and {24, 42} back in Task 11. A real List prints with square brackets: [2, 4, 6, 8]. Every Working callout that reports a list — Task 11 above, and Tasks 15 and 16 below — uses the brace notation, and the checkers accept either form.
Task 15. What is the value of:
Stream.of(1, 2, 3, 4, 5, 6, 7, 8).filter(x -> x % 2 == 0).toList();{2, 4, 6, 8}
Task 16. What is the value of:
Stream.of(1, 2, 3, 4, 5, 6, 7, 8).map(x -> x * x).toList();{1, 4, 9, 16, 25, 36, 49, 64}
Task 17. What is the value of:
List<String> list = Arrays.asList("apple", "banana", "cherry");
list.stream()
.map(String::toUpperCase)
.filter(s -> s.startsWith("A"))
.forEach(System.out::println);APPLE — only "apple" survives the startsWith("A") filter once upper-cased.
Task 18. What is the value of:
Stream<Integer> stream = Stream.iterate(1, n -> n * 2).limit(5);
Integer result = stream.reduce(0, (a, b) -> a + b);
System.out.println(result);31 — Stream.iterate(1, n -> n * 2).limit(5) produces 1, 2, 4, 8, 16, and \(1+2+4+8+16 = 31\).
Task 19. Convert the following method into streams:
static int sumOfSquareNumbers(List<String> words) {
int sum = 0;
for (String word : words) {
if (word.matches("[0-9]+")) {
int number = Integer.parseInt(word);
if (Math.sqrt(number) == Math.floor(Math.sqrt(number))) {
sum += number;
}
}
}
return sum;
}static int sumOfSquareNumbers(List<String> words) {
return words.stream()
.filter(word -> word.matches("[0-9]+"))
.mapToInt(Integer::parseInt)
.filter(number -> Math.sqrt(number) == Math.floor(Math.sqrt(number)))
.sum();
}The hint for this task points at filter, map, mapToInt, reduce and sum. Each if becomes a filter, the Integer.parseInt step becomes a mapToInt, and the sum accumulator becomes the terminal sum().
mapToInt (rather than map) is what makes the last step available: it produces an IntStream, which has sum(); a Stream<Integer> does not, and would need .reduce(0, Integer::sum) instead.
The return is required: a body that starts with words.stream() and no return would not compile for an int-returning method.
Task 20. What does this print?
List<String> words = Arrays.asList("cat", "dog", "elephant", "giraffe");
String details = words.stream()
.reduce("", (word1, word2) -> word1 + "-" + word2);
System.out.println(details);-cat-dog-elephant-giraffe — the identity "" is the first word1, so even the first element gets a leading - prepended.
Task 21. What does this print?
Stream<String> stream = Stream.of("hello", "world", "java");
stream.map(String::toUpperCase)
.forEach(System.out::print);HELLOWORLDJAVA — print (not println) concatenates every element with no separator.
From loop to pipeline
Task 19 is the one worth re-reading, because the conversion is mechanical once you see which construct maps to which stage. Pairing the two versions up row by row:
Figure 3: Task 19’s imperative method beside its stream solution, with each construct paired to the stage that replaces it. The code is split across rows with the enclosing method signature and braces dropped and intervening lines elided as ...; the last imperative row gathers the three accumulator lines, which are not adjacent in the method. The dashed arrow means is replaced by.
The reusable rule: the loop header becomes the source, each guard becomes a filter, each per-element computation becomes a map, and the accumulator becomes the terminal operation. Task 20’s reduce is the general case of that last step — sum() is just the special case for an IntStream.