Java NotesRohit’s interview study guide
Chapter 08

Lambdas and Streams

Lambdas and the functional interfaces they implement, method references, streams compared with JavaScript's array methods, collectors, flatMap and primitive streams, when parallel streams help, and stream gatherers (Java 24). Every example was run with Java 25 (Eclipse Temurin 25.0.5.1); the JavaScript comparisons were run with Node 26.

Try it yourself. For each example, make an empty folder, save every code box in it under the name in its caption, and type the $ lines of the Terminal box in that folder. Your output should match the page. The examples are compact source files (chapter 01), which import java.util, java.util.function and java.util.stream automatically.

8 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Lambdas and functional interfaces

Added

In JavaScript a function is a value: const isLong = s => s.length > 4 and you pass isLong around. Java has no function type. Instead, a lambda is a short way to write an object that implements an interface with exactly one abstract method, called a functional interface. Predicate<String> isLong = s -> s.length() > 4; creates an object whose test method runs s.length() > 4. You call it by its method name: isLong.test("mouse"), not isLong("mouse").

Before Java 8 you wrote the same thing as an anonymous inner class, five lines for one expression (chapter 01 shows one). A lambda is that class with the ceremony removed, and the compiler works out which interface it implements from where you use it (the target type). java.util.function has the standard shapes, so you rarely declare your own:

InterfaceMethodShapeExample
Function<T, R>applyT → Rs -> s.length()
BiFunction<T, U, R>apply(T, U) → R(a, b) -> a + b
Predicate<T>testT → booleans -> s.isEmpty()
Supplier<T>get() → T() -> new ArrayList<>()
Consumer<T>acceptT → nothings -> IO.println(s)
UnaryOperator<T> / BinaryOperator<T>applyT → T / (T, T) → Ts -> s.strip(), Integer::sum

There are also primitive versions (IntPredicate, ToIntFunction, IntBinaryOperator, …) that avoid boxing int into Integer. The mental model: a lambda is a one-method object, and the interface's name tells you how to call it. The one rule that surprises JavaScript developers comes next: a lambda can read local variables from the surrounding method only if they're effectively final, never reassigned after they're set.

Functions.java
@FunctionalInterface
interface PriceRule {
    double apply(double price);
}

void main() {
    Function<String, Integer> length = s -> s.length();
    Predicate<String> isLong = s -> s.length() > 4;
    Supplier<List<String>> fresh = () -> new ArrayList<>();
    Consumer<String> shout = s -> IO.println(s.toUpperCase() + "!");
    BinaryOperator<Integer> add = (a, b) -> a + b;

    IO.println(length.apply("keyboard") + " " + isLong.test("mouse") + " " + isLong.negate().test("mouse"));
    shout.accept("hello");
    IO.println(add.apply(2, 3));
    List<String> list = fresh.get();
    list.add("new");
    IO.println(list + " " + (fresh.get() != list));

    Function<String, String> clean = s -> s.strip();
    Function<String, Integer> cleanLength = clean.andThen(length);
    IO.println(cleanLength.apply("  mouse  "));

    PriceRule tenOff = price -> price * 0.9;
    PriceRule minusFive = price -> price - 5;
    double price = 100;
    IO.println(minusFive.apply(tenOff.apply(price)));
}
Terminal
$ java Functions.java
8 true false
HELLO!
5
[new] true
5
85.0
What’s happening
  1. Each lambda becomes an object of its target interface: length.apply("keyboard") runs s.length() and returns 8; isLong.test("mouse") is true (5 > 4), and negate(), a default method on Predicate, gives the opposite: false.
  2. shout.accept("hello") prints HELLO!; a Consumer returns nothing. add.apply(2, 3) gives 5.
  3. fresh is a Supplier: every get() runs the lambda again and builds a new list, which is why the second get() isn't the same object as list (true).
  4. andThen composes functions, like piping in JavaScript: clean.andThen(length) strips first, then measures. " mouse " becomes "mouse", length 5.
  5. PriceRule is our own functional interface; @FunctionalInterface is optional, but it makes the compiler reject the interface if someone adds a second abstract method. tenOff then minusFive turns 100 into 90.0 and then 85.0.
  6. Note how each call uses the interface's method name (apply, test, get, accept). That's the price of Java having no function types: the lambda is short, but the type that receives it decides how it's called.
AdvancedEffectively final captures

A JavaScript arrow function can change any variable it can see. A Java lambda can read local variables of the enclosing method, but only if they're effectively final: assigned once and never changed. The lambda gets a copy of the value, not the variable, so letting either side change it would make the copy and the variable disagree.

Counter.java
void main() {
    int count = 0;
    List.of("a", "b", "c").forEach(s -> count++);
    IO.println(count);
}
Terminal
$ java Counter.java
Counter.java:3: error: local variables referenced from a lambda expression must be final or effectively final
    List.of("a", "b", "c").forEach(s -> count++);
                                        ^
1 error
error: compilation failed
counter.mjs
let count = 0;
["a", "b", "c"].forEach(() => count++);
console.log(count);
Terminal
$ node counter.mjs
3
What’s happening
  1. Java: count++ inside the lambda would change a local variable of main, and the compiler refuses: "local variables referenced from a lambda expression must be final or effectively final".
  2. JavaScript: the arrow function closes over the variable itself, so all three calls increment the same count and it prints 3.
  3. The Java way is to not need the mutation: long count = list.stream().count();, or filter(…).count() for a condition. When you truly need a mutable counter inside a lambda (rare), an AtomicInteger or a field works, because the lambda then captures a reference that stays the same while the object it points to changes.
  4. Fields are different from local variables: a lambda in an instance method can read and change the object's fields freely, because it captures this, which never changes.
Advancedthis in a lambda and in an anonymous class

A lambda doesn't create a new scope for this: inside it, this means the enclosing object, like an arrow function in JavaScript. An anonymous class is a real new object, so its this is itself. This is a common interview contrast.

Greeter.java
public class Greeter {
    private final String name = "greeter";

    public String toString() {
        return "the Greeter";
    }

    void run() {
        Runnable lambda = () -> System.out.println("lambda this: " + this + ", name " + name);
        Runnable anonymous = new Runnable() {
            public void run() {
                System.out.println("anonymous this: " + this.getClass().getSimpleName().isEmpty() + ", name " + name);
            }
        };
        lambda.run();
        anonymous.run();
    }

    public static void main(String[] args) {
        new Greeter().run();
    }
}
Terminal
$ java Greeter.java
lambda this: the Greeter, name greeter
anonymous this: true, name greeter
What’s happening
  1. In the lambda, this is the Greeter whose run created it, so it prints the Greeter (its toString()).
  2. In the anonymous class, this is the anonymous Runnable object. Anonymous classes have an empty simple name, which is what isEmpty() shows (true). It can still read name, through the hidden reference every inner class keeps to its outer object.
  3. That hidden reference is why an anonymous class (or inner class) kept alive by a long-lived listener can keep its whole outer object from being garbage-collected. A lambda captures this only if its body uses this or a field: javap -p on a compiled class shows a lambda that reads a field compiled to an instance method, and one that doesn't to a static method.
  4. JavaScript parallel: an arrow function behaves like the lambda (this from the surrounding code), a function () {} callback like the anonymous class (its own this).
Does this compile? (capturing a loop variable)
Java
void main() {
    List<Supplier<Integer>> suppliers = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        suppliers.add(() -> i * 10);
    }
    suppliers.forEach(s -> IO.println(s.get()));
}
Show answer
Loop.java
void main() {
    List<Supplier<Integer>> suppliers = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        suppliers.add(() -> i * 10);
    }
    suppliers.forEach(s -> IO.println(s.get()));
}
Terminal
$ java Loop.java
Loop.java:4: error: local variables referenced from a lambda expression must be final or effectively final
        suppliers.add(() -> i * 10);
                            ^
1 error
error: compilation failed
What’s happening
  1. No. A classic for loop has one variable i that i++ changes, so it isn't effectively final, and the lambda can't capture it.
  2. JavaScript with var i is the famous bug where every callback sees the final value; let i makes a fresh binding per iteration. Java simply refuses to compile the ambiguous case.
  3. The fix is a fresh variable per iteration, int copy = i;, which is never changed, so the lambda can capture it. An enhanced for loop also works, because its variable is new for each iteration. Both are below.
Loop.java
void main() {
    List<Supplier<Integer>> suppliers = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        int copy = i;
        suppliers.add(() -> copy * 10);
    }
    for (int n : List.of(3, 4)) {
        suppliers.add(() -> n * 10);
    }
    suppliers.forEach(s -> IO.println(s.get()));
}
Terminal
$ java Loop.java
0
10
20
30
40
What’s happening
  1. Each lambda captured its own copy or n, so the values are 0, 10, 20, 30, 40.

#Method references

Added

A method reference is a lambda that only calls one existing method, written with ::. String::toUpperCase means s -> s.toUpperCase(); Integer::parseInt means s -> Integer.parseInt(s). There are four kinds, and the trick to reading them is to ask where the arguments go:

KindExampleEquivalent lambda
static methodInteger::parseInts -> Integer.parseInt(s)
instance method of a particular object (bound)prefix::concats -> prefix.concat(s)
instance method of an arbitrary object (unbound)String::toUpperCases -> s.toUpperCase()
constructorProduct::new(name, price) -> new Product(name, price)

The bound and unbound kinds look alike. In prefix::concat the receiver is fixed (the object in the variable prefix) and the lambda's argument becomes the method's argument. In String::toUpperCase there's no receiver yet, so the first argument becomes the receiver. JavaScript has no equivalent syntax; the nearest is passing Number.parseInt or obj.method.bind(obj).

Use a method reference when it reads better than the lambda, usually when the name says everything (map(Product::name), forEach(IO::println)). Keep the lambda when the reference would need a comment, or when you're passing extra arguments.

References.java
record Product(String name, int price) {
    boolean cheap() {
        return price < 50;
    }
}

void main() {
    Function<String, Integer> parse = Integer::parseInt;
    String prefix = "SKU-";
    Function<String, String> withPrefix = prefix::concat;
    Function<String, String> upper = String::toUpperCase;
    BiFunction<String, Integer, Product> make = Product::new;

    IO.println(parse.apply("42") + 1);
    IO.println(withPrefix.apply("kb1"));
    IO.println(upper.apply("mouse"));
    IO.println(make.apply("cable", 9));

    var products = List.of(new Product("keyboard", 49), new Product("monitor", 199), new Product("mouse", 19));
    products.stream()
            .filter(Product::cheap)
            .map(Product::name)
            .map(String::toUpperCase)
            .forEach(IO::println);

    Comparator<String> byLength = Comparator.comparing(String::length);
    IO.println(byLength.compare("ab", "abc") < 0);
}
Terminal
$ java References.java
43
SKU-kb1
MOUSE
Product[name=cable, price=9]
KEYBOARD
MOUSE
true
What’s happening
  1. Static: Integer::parseInt passes its argument to the static method: "42" becomes 42, plus 1 is 43.
  2. Bound: prefix::concat fixes the receiver to the string "SKU-", so apply("kb1") calls "SKU-".concat("kb1"): SKU-kb1.
  3. Unbound: String::toUpperCase has no receiver yet, so the argument becomes the receiver: "mouse".toUpperCase(). Product::cheap and Product::name in the stream work the same way, on each product.
  4. Constructor: Product::new matches the record's two-argument constructor, so make.apply("cable", 9) builds Product[name=cable, price=9].
  5. The stream keeps the cheap products (keyboard at 49 and mouse at 19), takes their names, uppercases them and prints each with IO::println (a static method reference). Then Comparator.comparing(String::length) builds a comparator from a key: "ab" is shorter, so compare is negative: true.
What does this print? (a bound reference to null)
Java
void main() {
    String text = null;
    Supplier<Integer> lambda = () -> text.length();
    IO.println("lambda created");
    Supplier<Integer> reference = text::length;
    IO.println("reference created");
}
Show answer
Bound.java
void main() {
    String text = null;
    Supplier<Integer> lambda = () -> text.length();
    IO.println("lambda created");
    Supplier<Integer> reference = text::length;
    IO.println("reference created");
}
Terminal
$ java Bound.java
lambda created
Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:220)
	at Bound.main(Bound.java:5)
What’s happening
  1. Creating the lambda doesn't run its body, so there's no problem yet: lambda created.
  2. A bound method reference evaluates its receiver when it's created, and the language requires a NullPointerException right there if the receiver is null. So text::length throws before reference created can print. The trace shows how: the compiler inserted an Objects.requireNonNull check on line 5.
  3. The lambda would only fail when someone calls lambda.get(). Same-looking code, failure at a different moment: worth knowing when a stack trace points at the line that creates a method reference.

#Streams compared with JavaScript array methods

Added

A stream is a pipeline over a source of elements (a collection, an array, a range, a file's lines): a chain of intermediate operations (filter, map, sorted, distinct, limit) that each return a new stream, ended by one terminal operation (toList, forEach, count, reduce, collect, findFirst) that produces the result. It looks like JavaScript's arr.filter(…).map(…), but it runs very differently:

  • JavaScript array methods are eager. filter loops over the whole array and builds a new array; then map loops over that and builds another. Each step finishes before the next starts.
  • Streams are lazy. Intermediate operations only describe the work. Nothing runs until the terminal operation, and then each element travels through the whole pipeline before the next one starts, so findFirst or limit can stop the moment it has an answer. (JavaScript's newer iterator helpers, such as array.values().filter(…), work this way too.)
  • A stream runs once. After its terminal operation it's used up; you get a new one from the source.
  • A stream doesn't change its source. It reads from it and produces a new result, which is why toList() (Java 16) returns a new, unmodifiable list.

The mental model: an array method chain is a series of buckets you pour from one into the next; a stream is an assembly line where each item goes from station to station, and the line only starts when someone at the end asks for something.

Lazy.java
void main() {
    var first = Stream.of("kiwi", "banana", "cherry", "fig")
            .filter(s -> {
                IO.println("filter " + s);
                return s.length() > 4;
            })
            .map(s -> {
                IO.println("map " + s);
                return s.toUpperCase();
            })
            .findFirst();
    IO.println("result " + first.orElseThrow());
}
Terminal
$ java Lazy.java
filter kiwi
filter banana
map banana
result BANANA
lazy.mjs
const first = ["kiwi", "banana", "cherry", "fig"]
  .filter((s) => {
    console.log("filter " + s);
    return s.length > 4;
  })
  .map((s) => {
    console.log("map " + s);
    return s.toUpperCase();
  })[0];
console.log("result " + first);
Terminal
$ node lazy.mjs
filter kiwi
filter banana
filter cherry
filter fig
map banana
map cherry
result BANANA
What’s happening
  1. Java: findFirst asks the pipeline for one element. kiwi goes through filter and is rejected (length 4), so it never reaches map.
  2. banana passes filter and goes straight on to map, which uppercases it. findFirst has its answer, so the stream stops: cherry and fig are never looked at. Two elements filtered, one mapped.
  3. JavaScript: filter runs over all four strings first and builds ["banana", "cherry"]; then map runs over both and builds ["BANANA", "CHERRY"]; then [0] takes the first. Four filter calls and two map calls for the same answer.
  4. Note the order of the printed lines. Java interleaves filter and map per element (vertical processing); JavaScript finishes each step for all elements first (horizontal).
  5. Both print result BANANA. The difference is the work done to get there, which matters with large sources, expensive steps, or infinite streams.
AdvancedInfinite streams, single use, and toList

Because streams are lazy, the source can be infinite as long as something cuts it short. And because a stream is a one-time pipeline, reusing it is an error.

Infinite.java
void main() {
    var powers = Stream.iterate(1, n -> n * 2)
            .takeWhile(n -> n < 1000)
            .toList();
    IO.println(powers);

    var firstThreeOdd = IntStream.iterate(1, n -> n + 1)
            .filter(n -> n % 2 == 1)
            .limit(3)
            .boxed()
            .toList();
    IO.println(firstThreeOdd);

    Stream<String> names = Stream.of("ana", "li");
    IO.println(names.count());
    try {
        names.count();
    } catch (IllegalStateException e) {
        IO.println(e.getMessage());
    }

    var fromList = new ArrayList<>(List.of(3, 1, 2));
    var sorted = fromList.stream().sorted().toList();
    IO.println(fromList + " " + sorted);
}
Terminal
$ java Infinite.java
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
[1, 3, 5]
2
stream has already been operated upon or closed
[3, 1, 2] [1, 2, 3]
What’s happening
  1. Stream.iterate(1, n -> n * 2) is an endless stream of powers of two. takeWhile (Java 9) passes elements while the condition holds and ends the stream at the first one that fails (1024), so toList() finishes: [1, 2, 4, …, 512].
  2. The second pipeline is endless too, but limit(3) stops it after three odd numbers. IntStream holds plain ints; boxed() turns them into Integers so they can go in a List.
  3. names.count() consumes the stream and prints 2. The second count() throws IllegalStateException: "stream has already been operated upon or closed". In JavaScript you can call .filter on the same array as often as you like; a Java stream is not a collection, it's a single trip over one.
  4. sorted() didn't touch fromList, which is still [3, 1, 2]; the sorted result is a new list [1, 2, 3]. (Unlike JavaScript's arr.sort(), which sorts in place.)
What does this print? (no terminal operation, and count)
Java
void main() {
    Stream.of(1, 2, 3).map(n -> {
        IO.println("map " + n);
        return n * 2;
    });
    IO.println("after the first pipeline");

    long n = Stream.of(1, 2, 3).map(x -> {
        IO.println("counting " + x);
        return x;
    }).count();
    IO.println("count " + n);
}
Show answer
Nothing.java
void main() {
    Stream.of(1, 2, 3).map(n -> {
        IO.println("map " + n);
        return n * 2;
    });
    IO.println("after the first pipeline");

    long n = Stream.of(1, 2, 3).map(x -> {
        IO.println("counting " + x);
        return x;
    }).count();
    IO.println("count " + n);
}
Terminal
$ java Nothing.java
after the first pipeline
count 3
What’s happening
  1. The first pipeline has no terminal operation, so map never runs: nothing is printed except after the first pipeline. This is the classic "my stream doesn't do anything" bug.
  2. The second has a terminal operation, count(), and still prints no counting lines. The documentation allows count() to skip the pipeline when it can compute the count from the source directly: Stream.of(1, 2, 3) knows its size, and map can't change the number of elements, so the JDK just answers 3.
  3. Lesson: never put side effects you depend on inside intermediate operations. With a filter in the pipeline, the count can't be known in advance and the lambdas would run.
What does this print? (peek and sorted)
Java
void main() {
    Stream.of(3, 1, 2)
            .peek(n -> IO.println("peek " + n))
            .sorted()
            .forEach(n -> IO.println("got " + n));
}
Show answer
Peek.java
void main() {
    Stream.of(3, 1, 2)
            .peek(n -> IO.println("peek " + n))
            .sorted()
            .forEach(n -> IO.println("got " + n));
}
Terminal
$ java Peek.java
peek 3
peek 1
peek 2
got 1
got 2
got 3
What’s happening
  1. peek lets you look at each element as it passes, mostly for debugging.
  2. Most operations pass elements on one at a time, but sorted() is a stateful barrier: it can't emit anything until it has seen every element. So all three peek lines print first, in the source order 3, 1, 2.
  3. Then sorted emits 1, 2, 3 to forEach: got 1, got 2, got 3.
  4. Without sorted, the output would interleave (peek 3, got 3, peek 1, …), as in the lazy example above.

#Collectors

Added

toList() covers the simple case. For anything else, the terminal operation collect(collector) takes a recipe from the Collectors class: groupingBy (like Lodash's groupBy, or JavaScript's newer Object.groupBy and Map.groupBy), partitioningBy (a groupingBy into exactly true and false), toMap, joining (like array.join), counting, summingInt, averagingDouble, mapping and more. Collectors nest: groupingBy(category, counting()) groups and then counts each group, a "downstream" collector. That nesting is what makes them powerful, and what interviewers like to ask you to write.

The mental model: a collector is a reduce with a name. It says how to start an empty result, how to add one element to it, and (for parallel streams) how to merge two partial results.

Two traps to know: groupingBy returns a HashMap by default, so the groups come out in no particular order (pass TreeMap::new to sort them by key); and toMap throws IllegalStateException on a duplicate key unless you give it a merge function.

Report.java
record Order(String customer, String category, int amount) {}

void main() {
    var orders = List.of(
            new Order("ana", "books", 30),
            new Order("li", "games", 120),
            new Order("ana", "games", 60),
            new Order("sam", "books", 15),
            new Order("li", "books", 45));

    Map<String, Long> countByCategory = orders.stream()
            .collect(Collectors.groupingBy(Order::category, TreeMap::new, Collectors.counting()));
    IO.println("count: " + countByCategory);

    Map<String, Integer> spendByCustomer = orders.stream()
            .collect(Collectors.groupingBy(Order::customer, TreeMap::new, Collectors.summingInt(Order::amount)));
    IO.println("spend: " + spendByCustomer);

    Map<String, List<String>> customersByCategory = orders.stream()
            .collect(Collectors.groupingBy(Order::category, TreeMap::new,
                    Collectors.mapping(Order::customer, Collectors.toList())));
    IO.println("who: " + customersByCategory);

    Map<Boolean, List<Integer>> bigOrSmall = orders.stream()
            .collect(Collectors.partitioningBy(o -> o.amount() >= 50,
                    Collectors.mapping(Order::amount, Collectors.toList())));
    IO.println("partition: " + bigOrSmall);

    String customers = orders.stream().map(Order::customer).distinct().sorted()
            .collect(Collectors.joining(", ", "[", "]"));
    IO.println("customers: " + customers);
}
Terminal
$ java Report.java
count: {books=3, games=2}
spend: {ana=90, li=165, sam=15}
who: {books=[ana, sam, li], games=[li, ana]}
partition: {false=[30, 15, 45], true=[120, 60]}
customers: [ana, li, sam]
What’s happening
  1. groupingBy(Order::category, TreeMap::new, counting()): the key comes from category, the map is a TreeMap (so keys print sorted), and each group is reduced with counting(). Three books orders, two games: {books=3, games=2}. Counts are Long.
  2. summingInt(Order::amount) reduces each customer's group to a total: ana 30 + 60 = 90, li 120 + 45 = 165, sam 15.
  3. mapping(Order::customer, toList()) transforms each element before collecting it, so the groups hold customer names instead of whole orders, in encounter order: books were bought by ana, sam, li.
  4. partitioningBy always returns both keys, false and true, even if one list is empty; groupingBy on a boolean would leave a missing group out.
  5. joining(", ", "[", "]") is array.join(", ") plus a prefix and suffix. distinct() and sorted() first give [ana, li, sam].
AdvancedtoMap and duplicate keys

toMap(keyMapper, valueMapper) builds a map from each element, and assumes keys are unique. With real data they often aren't.

Index.java
record Order(String customer, String category, int amount) {}

void main() {
    var orders = List.of(
            new Order("ana", "books", 30),
            new Order("li", "games", 120),
            new Order("ana", "games", 60));

    try {
        Map<String, Integer> byCustomer = orders.stream()
                .collect(Collectors.toMap(Order::customer, Order::amount));
        IO.println(byCustomer);
    } catch (IllegalStateException e) {
        IO.println(e.getMessage());
    }

    Map<String, Integer> totals = orders.stream()
            .collect(Collectors.toMap(Order::customer, Order::amount, Integer::sum, TreeMap::new));
    IO.println("summed: " + totals);

    Map<String, Order> latest = orders.stream()
            .collect(Collectors.toMap(Order::customer, o -> o, (first, second) -> second, LinkedHashMap::new));
    IO.println("last per customer: " + latest.values());
}
Terminal
$ java Index.java
Duplicate key ana (attempted merging values 30 and 60)
summed: {ana=90, li=120}
last per customer: [Order[customer=ana, category=games, amount=60], Order[customer=li, category=games, amount=120]]
What’s happening
  1. The first toMap meets ana twice and throws IllegalStateException. The message names the key and both values, which is what you'd look for in a log: "Duplicate key ana (attempted merging values 30 and 60)".
  2. The third argument is the merge function: what to do when a key repeats. Integer::sum adds them: ana 30 + 60 = 90. The fourth argument picks the map type (TreeMap::new for sorted keys).
  3. (first, second) -> second keeps the later element, which is how you build "latest order per customer". LinkedHashMap::new keeps the keys in the order they first appeared.
  4. If duplicates are a bug in your data, the exception is a good thing; if they're expected, decide explicitly with a merge function. Never write (a, b) -> a without thinking about which one you actually want.

#flatMap, reduce and primitive streams

Added

flatMap maps each element to a stream and flattens the results into one stream: orders to their lines, sentences to their words. It's JavaScript's arr.flatMap(…), except that the function returns a stream (order.lines().stream()) rather than an array. reduce folds the elements into one value, like arr.reduce((acc, x) => …, initial): the initial value is called the identity, and it must really be neutral (0 for addition, 1 for multiplication), because in parallel streams it's used more than once.

Primitive streams (IntStream, LongStream, DoubleStream) hold int, long and double values directly. A Stream<Integer> holds Integer objects, so every number is boxed into an object and unboxed again for arithmetic, which costs memory and time on big streams. Primitive streams avoid that and add the numeric operations you'd expect: sum(), average(), max(), summaryStatistics(), and IntStream.range(0, n), the stream version of a for loop. You switch with mapToInt (to primitive) and boxed() or mapToObj (back to objects).

The mental model: flatMap is unpacking boxes onto one conveyor belt; reduce is a running total; a primitive stream is the same belt carrying bare numbers instead of numbers in envelopes.

Totals.java
record Line(String product, int quantity, int unitPrice) {}
record Order(String id, List<Line> lines) {}

void main() {
    var orders = List.of(
            new Order("o-1", List.of(new Line("keyboard", 1, 49), new Line("mouse", 2, 19))),
            new Order("o-2", List.of(new Line("monitor", 1, 199))),
            new Order("o-3", List.of()));

    List<String> products = orders.stream()
            .flatMap(o -> o.lines().stream())
            .map(Line::product)
            .toList();
    IO.println(products);

    int revenue = orders.stream()
            .flatMap(o -> o.lines().stream())
            .mapToInt(l -> l.quantity() * l.unitPrice())
            .sum();
    IO.println("revenue " + revenue);

    int units = orders.stream()
            .flatMap(o -> o.lines().stream())
            .map(Line::quantity)
            .reduce(0, Integer::sum);
    IO.println("units " + units);

    var stats = orders.stream()
            .mapToInt(o -> o.lines().size())
            .summaryStatistics();
    IO.println("lines per order: " + stats);

    IO.println("average of nothing: " + IntStream.empty().average());
    IO.println("squares: " + IntStream.rangeClosed(1, 5).map(n -> n * n).boxed().toList());
}
Terminal
$ java Totals.java
[keyboard, mouse, monitor]
revenue 286
units 4
lines per order: IntSummaryStatistics{count=3, sum=3, min=0, average=1.000000, max=2}
average of nothing: OptionalDouble.empty
squares: [1, 4, 9, 16, 25]
What’s happening
  1. flatMap(o -> o.lines().stream()) turns three orders into one stream of four lines. The empty order o-3 contributes nothing. Mapping to names gives [keyboard, mouse, monitor].
  2. mapToInt switches to an IntStream of line totals (49, 38, 199), and sum() adds them as plain ints: 286.
  3. reduce(0, Integer::sum) does the same kind of sum on boxed Integers, with 0 as the identity: quantities 1 + 2 + 1 = 4. It works, but mapToInt(Line::quantity).sum() would be clearer and avoid boxing.
  4. summaryStatistics() computes count, sum, min, average and max in one pass: the orders have 2, 1 and 0 lines.
  5. average() returns an OptionalDouble, because the average of nothing is undefined: it prints OptionalDouble.empty instead of JavaScript's NaN from 0 / 0.
  6. IntStream.rangeClosed(1, 5) is 1 to 5 inclusive (range excludes the end), and boxed() turns the ints back into Integers for toList().
AdvancedWhy reduce needs a real identity

In a sequential stream, a wrong identity looks like a starting value: reduce(10, Integer::sum) adds 10 once. In a parallel stream, the work is split into chunks, each chunk starts from the identity, and then the chunks are combined, so the 10 is added once per chunk.

Identity.java
void main() {
    int sequential = Stream.of(1, 2, 3, 4).reduce(10, Integer::sum);
    int parallel = Stream.of(1, 2, 3, 4).parallel().reduce(10, Integer::sum);
    IO.println("sequential " + sequential + ", parallel " + parallel);

    int right = 10 + Stream.of(1, 2, 3, 4).parallel().reduce(0, Integer::sum);
    IO.println("identity 0, then add 10: " + right);
}
Terminal
$ java Identity.java
sequential 20, parallel 50
identity 0, then add 10: 20
What’s happening
  1. Sequentially: 10 + 1 + 2 + 3 + 4 = 20, which hides the mistake.
  2. In parallel, the four elements were split into four chunks on this machine; each computed 10 + element, and combining them gave 11 + 12 + 13 + 14 = 50. The exact number depends on how the stream is split, which depends on the number of CPU cores: the point is that it isn't 20.
  3. The identity must satisfy identity + x == x. Use 0 for sums and add any starting value outside the stream.
  4. The same rule applies to the accumulator: it must be associative ((a + b) + c == a + (b + c)), or splitting changes the answer. The next topic shows subtraction going wrong.

#Parallel streams

Added

Add .parallel() (or use collection.parallelStream()) and the stream splits its source into chunks, processes them on several threads, and combines the results. The threads come from the JVM-wide common ForkJoinPool, shared by every parallel stream in the process. Its default size is based on the number of CPU cores, and the thread that runs the terminal operation helps out too.

That design gives three rules. Parallel only helps for CPU-heavy work on big data with a source that splits well (arrays, ArrayList, IntStream.range; not LinkedList, Stream.iterate or I/O). It hurts for small streams, where splitting and combining cost more than the work, and for blocking I/O, which ties up the shared pool for everyone else (in a Spring app, that includes every other request using parallel streams). And the lambdas must have no side effects on shared state, because they now run on several threads at once: adding to an ArrayList from a parallel forEach loses elements or throws.

Compared with Node.js: there's nothing like this in JavaScript, which runs your code on one thread (worker threads exist but don't share objects). Here the parallelism is real, and so are the races. The mental model: parallel is a promise to the JDK that your pipeline doesn't care which thread runs which element, or in what order. Keep that promise, and measure before assuming it's faster.

Parallel.java
void main() {
    Set<String> threads = IntStream.range(0, 64).parallel()
            .mapToObj(i -> {
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                return Thread.currentThread().getName().replaceAll("\\d+$", "N");
            })
            .collect(Collectors.toCollection(TreeSet::new));
    IO.println("threads used: " + threads);

    long sequential = LongStream.rangeClosed(1, 2_000_000).map(n -> n * n % 7).sum();
    long parallel = LongStream.rangeClosed(1, 2_000_000).parallel().map(n -> n * n % 7).sum();
    IO.println("same sum: " + (sequential == parallel));

    var unsafe = new ArrayList<Integer>();
    boolean crashed = false;
    try {
        IntStream.range(0, 100_000).parallel().forEach(unsafe::add);
    } catch (ArrayIndexOutOfBoundsException e) {
        crashed = true;
    }
    IO.println("forEach into ArrayList kept all 100000: " + (!crashed && unsafe.size() == 100_000));

    List<Integer> safe = IntStream.range(0, 100_000).parallel().boxed().toList();
    IO.println("toList kept all, in order: " + (safe.size() == 100_000 && safe.get(99_999) == 99_999));

    int minusSequential = IntStream.rangeClosed(1, 100).reduce(0, (a, b) -> a - b);
    int minusParallel = IntStream.rangeClosed(1, 100).parallel().reduce(0, (a, b) -> a - b);
    IO.println("subtraction, same answer: " + (minusSequential == minusParallel));
}
Terminal
$ java Parallel.java
threads used: [ForkJoinPool.commonPool-worker-N, main]
same sum: true
forEach into ArrayList kept all 100000: false
toList kept all, in order: true
subtraction, same answer: false
What’s happening
  1. Each of the 64 elements sleeps briefly and reports its thread's name, with the trailing number replaced by N so the output is stable. Two kinds of thread did the work: ForkJoinPool.commonPool-worker-N threads and main, the thread that called the terminal operation and helps with the chunks.
  2. A pure, CPU-only pipeline (n * n % 7, summed) gives the same sum sequentially and in parallel. This is the case parallel streams are for.
  3. forEach(unsafe::add) calls ArrayList.add from many threads at once. ArrayList isn't thread-safe: concurrent adds overwrite each other's slots or hit the array while it's being resized, so the list ends up short, or add throws ArrayIndexOutOfBoundsException. Either way, false. (This ran on a machine with many cores; on a single core it might happen to work, which is exactly why such bugs escape testing.)
  4. Letting the stream build the result with toList() is safe: each thread fills its own chunk and the stream combines them in encounter order, so all 100,000 are there and the last is 99999.
  5. Subtraction isn't associative, so splitting the range changes the result: false. Sequentially it's 0 - 1 - 2 - … - 100 = -5050; in parallel the chunks are subtracted from each other and the answer depends on how the work was split.
AdvancedGotcha: blocking calls in parallel streams

#Stream gatherers

Added

Streams have a fixed set of intermediate operations (map, filter, flatMap, distinct, sorted, limit, …). Until recently, anything else, like "group into batches of 3" or "a running total", meant collecting into a list and looping. Java 24 added gatherers (JEP 485): stream.gather(gatherer) is a general-purpose intermediate operation, and a gatherer can keep state, emit any number of elements per input, and stop early. They're final in Java 24 and in Java 25 LTS; on Java 21 they don't exist.

The class Gatherers has five built-in ones:

GathererWhat it doesExample result
windowFixed(n)batches of n (the last may be shorter)1..7 → [1, 2, 3], [4, 5, 6], [7]
windowSliding(n)every run of n consecutive elements1..4 → [1, 2], [2, 3], [3, 4]
fold(initial, folder)one result from all elements, emitted at the endlike reduce, but the result type can differ
scan(initial, scanner)every intermediate result of a foldrunning totals
mapConcurrent(max, mapper)runs mapper on virtual threads, at most max at once, keeping orderparallel I/O calls

The mental model: a gatherer is a custom station on the assembly line: it receives each item, can remember things between items, and decides what (if anything) to pass down the line. JavaScript has no built-in equivalent; you'd write a generator function.

Windows.java
void main() {
    var numbers = List.of(1, 2, 3, 4, 5, 6, 7);

    IO.println("batches: " + numbers.stream().gather(Gatherers.windowFixed(3)).toList());
    IO.println("pairs: " + numbers.stream().limit(4).gather(Gatherers.windowSliding(2)).toList());

    var temps = List.of(20.0, 22.0, 27.0, 25.0, 21.0);
    var movingAverage = temps.stream()
            .gather(Gatherers.windowSliding(3))
            .map(w -> w.stream().mapToDouble(Double::doubleValue).average().orElseThrow())
            .toList();
    IO.println("3-day average: " + movingAverage);

    IO.println("running total: " + numbers.stream().gather(Gatherers.scan(() -> 0, Integer::sum)).toList());
    IO.println("joined: " + numbers.stream().gather(Gatherers.fold(() -> "", (acc, n) -> acc + n)).findFirst().orElseThrow());

    var lengths = Stream.of("ana", "maya", "rohit")
            .gather(Gatherers.mapConcurrent(2, name -> name + ":" + name.length()))
            .toList();
    IO.println("mapConcurrent keeps order: " + lengths);
}
Terminal
$ java Windows.java
batches: [[1, 2, 3], [4, 5, 6], [7]]
pairs: [[1, 2], [2, 3], [3, 4]]
3-day average: [23.0, 24.666666666666668, 24.333333333333332]
running total: [1, 3, 6, 10, 15, 21, 28]
joined: 1234567
mapConcurrent keeps order: [ana:3, maya:4, rohit:5]
What’s happening
  1. windowFixed(3) groups the seven numbers into lists of three; the last window is shorter: [[1, 2, 3], [4, 5, 6], [7]]. In a real system that's "send in batches of 3".
  2. windowSliding(2) on the first four numbers produces each pair of neighbours: [1, 2], [2, 3], [3, 4], useful for differences between consecutive readings.
  3. A moving average is windowSliding(3) followed by averaging each window: (20 + 22 + 27) / 3 = 23.0, then 24.666…, then 24.333…. Before gatherers this needed index arithmetic over a list.
  4. scan(() -> 0, Integer::sum) emits the running total after each element: 1, 3, 6, 10, 15, 21, 28. fold emits only the final value, once, which is why it needs findFirst() to get it out: "1234567".
  5. mapConcurrent(2, …) runs the mapper on virtual threads, at most two at a time, but delivers results in the original order: [ana:3, maya:4, rohit:5]. With a real HTTP call as the mapper, that's bounded, ordered, concurrent I/O in one line.
AdvancedWriting your own gatherer

A gatherer is built from an initializer (creates the state), an integrator (called for each element with the state and a downstream to push results to) and optionally a finisher (called at the end). Gatherer.ofSequential builds one that runs in order. This one drops consecutive duplicates, like the Unix uniq command, which no built-in stream operation does (distinct() drops all duplicates).

Uniq.java
<T> Gatherer<T, ?, T> dropRepeats() {
    class State {
        T previous;
        boolean started;
    }
    return Gatherer.<T, State, T>ofSequential(
            State::new,
            Gatherer.Integrator.ofGreedy((state, element, downstream) -> {
                if (state.started && Objects.equals(state.previous, element)) {
                    return true;
                }
                state.started = true;
                state.previous = element;
                return downstream.push(element);
            }));
}

void main() {
    var readings = List.of("ok", "ok", "warn", "warn", "warn", "ok", "error", "error");
    IO.println("dropRepeats: " + readings.stream().gather(dropRepeats()).toList());
    IO.println("distinct:    " + readings.stream().distinct().toList());
}
Terminal
$ java Uniq.java
dropRepeats: [ok, warn, ok, error]
distinct:    [ok, warn, error]
What’s happening
  1. State is a local class holding what the gatherer remembers between elements: the previous element and whether there was one. The initializer State::new creates a fresh one for each stream run.
  2. The integrator is called once per element. If the element equals the previous one, it returns true ("keep sending me elements") without pushing anything, so the repeat is dropped.
  3. Otherwise it records the element and downstream.push(element) passes it on. push returns false when the downstream doesn't want more (after a limit, say), and returning that value lets the stream stop early.
  4. ofGreedy tells the stream this integrator never stops early by itself, which lets the JDK optimise a little. The result keeps the changes in state: [ok, warn, ok, error], where distinct() gives [ok, warn, error] and loses the fact that the status went back to ok.

#Your turn: streams

Added
Your turn: the three most expensive products

Given products with a name, category and price, print the names of the three most expensive, most expensive first, in one stream.

Show answer
Top.java
record Product(String name, String category, int price) {}

void main() {
    var products = List.of(
            new Product("keyboard", "input", 49),
            new Product("monitor", "display", 199),
            new Product("mouse", "input", 19),
            new Product("laptop", "computer", 999),
            new Product("webcam", "video", 89));

    List<String> top = products.stream()
            .sorted(Comparator.comparingInt(Product::price).reversed())
            .limit(3)
            .map(Product::name)
            .toList();
    IO.println(top);
}
Terminal
$ java Top.java
[laptop, monitor, webcam]
What’s happening
  1. sorted(Comparator.comparingInt(Product::price).reversed()) orders by price, highest first: laptop 999, monitor 199, webcam 89, keyboard 49, mouse 19.
  2. limit(3) keeps the first three and ends the stream there.
  3. map(Product::name) and toList() give [laptop, monitor, webcam]. The original products list is untouched.
Your turn: average price per category

Using the same products, print the average price per category, with categories in alphabetical order.

Show answer
Average.java
record Product(String name, String category, int price) {}

void main() {
    var products = List.of(
            new Product("keyboard", "input", 49),
            new Product("monitor", "display", 199),
            new Product("mouse", "input", 19),
            new Product("laptop", "computer", 999),
            new Product("webcam", "video", 89));

    Map<String, Double> average = products.stream()
            .collect(Collectors.groupingBy(Product::category, TreeMap::new,
                    Collectors.averagingInt(Product::price)));
    IO.println(average);
}
Terminal
$ java Average.java
{computer=999.0, display=199.0, input=34.0, video=89.0}
What’s happening
  1. groupingBy(Product::category, TreeMap::new, …) groups by category into a sorted map.
  2. averagingInt(Product::price) is the downstream collector: it reduces each group to the average of its prices, as a Double.
  3. input has keyboard (49) and mouse (19), so its average is 34.0; the others have one product each.
Your turn: all the distinct words

Given a few sentences, print every distinct word in lower case, sorted, using flatMap.

Show answer
Words.java
void main() {
    var sentences = List.of("The cat sat", "the hat", "A cat and a hat");

    List<String> words = sentences.stream()
            .flatMap(s -> Arrays.stream(s.split(" ")))
            .map(String::toLowerCase)
            .distinct()
            .sorted()
            .toList();
    IO.println(words);
}
Terminal
$ java Words.java
[a, and, cat, hat, sat, the]
What’s happening
  1. split(" ") turns each sentence into an array of words, and Arrays.stream turns that array into a stream; flatMap joins the three streams into one of ten words.
  2. toLowerCase makes The and the the same word, so distinct() can drop the repeats.
  3. sorted() orders them alphabetically: [a, and, cat, hat, sat, the].

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.