Skip to content
Visual explainer 6h to learn 5 steps

Lambdas, streams & Optional

Transform data with streams instead of manual loops where it reads better.

By Invicly Tech, , in Backend Java Development. About 10 minutes to read.

Topic 5 of 29

In short

Lambdas are short anonymous functions, and streams chain them into readable data pipelines. Optional makes a possibly missing value explicit instead of returning null.

Explained simply

A lambda is a small function you can write inline and pass around like a value. x -> x * 2 means: take x, give back x times two. Before Java 8 you needed a whole anonymous class for this, which took five lines instead of one.

A stream is a pipeline for data. You start from a source, such as a list, then add steps: keep only some items (filter), change each item (map), and finally collect the results. You describe what you want, and the stream does the looping for you.

Streams do not change the original list. They read from it and produce something new, like a new list, a map or a single number. This makes code easier to reason about, because data is not modified in many places.

Optional is a small box that either holds a value or is empty. A method that might not find anything, like findUserByEmail, can return Optional<User> instead of null. The caller then has to decide what to do when the box is empty, which prevents many NullPointerExceptions.

Press Play on a diagram to walk through it one step at a time.

FlowA stream pipeline
  1. 1
    Source

    orders.stream() from a collection

  2. 2
    filter

    Keep elements matching a predicate

  3. 3
    map

    Transform each element to a new value

  4. 4
    Terminal operation

    collect, reduce, count or forEach starts the work

  5. 5
    Result

    A list, map, number or Optional

CompareSame task as a loop and as a stream
for loop
  • Says how: index, temp list, add
  • Easy to break and continue
  • Handles checked exceptions simply
  • Can mutate several variables
Stream pipeline
  • Says what: filter, map, collect
  • No temporary mutable list
  • Easy to add grouping or sorting
  • Lazy and can stop early

In depth

Functional interfaces and method references

A lambda is always an implementation of a functional interface: an interface with exactly one abstract method. java.util.function provides the common shapes. Function<T, R> turns a T into an R. Predicate<T> returns a boolean. Consumer<T> takes a value and returns nothing. Supplier<T> takes nothing and returns a value. BiFunction, UnaryOperator and BinaryOperator cover two inputs or same-type results.

A lambda may read local variables from the surrounding method only if they are effectively final, meaning never reassigned. That is why count++ inside a lambda does not compile. When a lambda just calls one existing method, a method reference is shorter and often clearer. There are four kinds, shown in the diagram.

  • Predicate<String> empty = String::isEmpty
  • Function<String, Integer> len = String::length
  • Supplier<List<String>> make = ArrayList::new
MapFour kinds of method reference
Method reference
  • Static method
    • Integer::parseInt
    • same as s -> Integer.parseInt(s)
  • Method of a given object
    • System.out::println
    • same as x -> System.out.println(x)
  • Method of the argument
    • String::toUpperCase
    • same as s -> s.toUpperCase()
  • Constructor
    • ArrayList::new
    • same as () -> new ArrayList<>()

Laziness: one element at a time

Intermediate operations like filter and map only describe work. Nothing happens until a terminal operation such as collect, count, findFirst or forEach asks for results. Then each element travels through the whole pipeline before the next one starts. A stream does not run filter on the whole list, then map on the whole list.

This lets short-circuit operations stop early. findFirst, anyMatch, allMatch, noneMatch and limit stop pulling elements as soon as they know the answer, so a pipeline over a million items may only touch three. It also means a stream can even be infinite, like Stream.iterate(1, x -> x * 2), as long as something like limit(10) ends it. Operations such as sorted and distinct must see all elements first, so they break this one-at-a-time flow.

Sequencefilter(even).map(x * 10).findFirst() on 1, 2, 3, 4
Source
filter
map
findFirst
  1. 1sends 1
    Source to filter: sends 1
  2. 21 rejected, next please
    filter to Source: 1 rejected, next please
  3. 3sends 2
    Source to filter: sends 2
  4. 42 passes
    filter to map: 2 passes
  5. 520
    map to findFirst: 20
  6. 6done: 3 and 4 never read
    findFirst to Source: done: 3 and 4 never read

Collectors you will use every week

Stream.toList() (Java 16) returns an unmodifiable list, which is usually what you want. Collectors.toList() makes no promise about mutability. Collectors.toMap(keyFn, valueFn) throws IllegalStateException when two elements produce the same key; pass a third argument, a merge function such as (a, b) -> a, to decide which value wins.

groupingBy(classifier) builds a Map from key to List of elements. Its second argument, a downstream collector, says what to do with each group: counting() gives a Long count, summingInt and averagingDouble give numbers, mapping(fn, toList()) keeps only one field. partitioningBy(predicate) is a special case that always returns a Map with the keys true and false. joining(", ") concatenates strings. groupingBy uses a HashMap; pass TreeMap::new as the middle argument when you want sorted keys.

  • groupingBy(Order::city, counting())
  • groupingBy(Order::city, TreeMap::new, toList())
  • partitioningBy(o -> o.total() > 100)
  • toMap(User::id, u -> u, (a, b) -> a)

Using Optional well

Optional was designed as a return type for methods that may have no result. Do not use it for fields, method parameters or collections; an empty list already means no items. Create one with Optional.of(value), which throws on null, or Optional.ofNullable(value) when null is possible.

Unwrap it safely. map and filter transform the value only if present. flatMap is for functions that already return an Optional. orElse(default) gives a fallback, but its argument is always evaluated, even when the value is present. If the fallback is expensive, such as a database call, use orElseGet(() -> loadDefault()), which runs only when needed. orElseThrow() throws NoSuchElementException, and orElseThrow(() -> new NotFoundException(id)) throws your own exception. ifPresentOrElse handles both cases in one call.

Primitive streams, parallel streams and when to use a loop

A Stream<Integer> boxes every number into an object. IntStream, LongStream and DoubleStream work with raw primitives and offer sum(), average() and summaryStatistics(). Switch with mapToInt(Order::quantity), and go back with boxed(). IntStream.range(0, n) replaces many counting loops.

parallelStream() splits the work across the common ForkJoinPool, which has about one thread per CPU core. It only helps for large, CPU-heavy work with no shared state, and it can hurt in a web server where all requests share that pool. Measure before using it.

Plain loops are still better when you need to break out early with complex conditions, update several variables, or call methods that throw checked exceptions. Use streams where they read like a sentence.

Learn it in 5 short steps

About 1h 10m each. Track them with a timer in your plan.

  1. 1
    Write lambdas and method references~1h 10m
  2. 2
    Use map, filter and reduce~1h 10m
  3. 3
    Group data with Collectors.groupingBy~1h 10m
  4. 4
    Return Optional instead of null~1h 10m
  5. 5
    Refactor loops into streams~1h 10m

Key points

  • Intermediate operations are lazy; nothing runs until a terminal operation is called.
  • A stream can be consumed only once; create a new one to reuse the source.
  • Collectors.groupingBy builds a Map from a key function in one line.
  • Return Optional for maybe-missing results; never call get() without checking.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
record Order(String customer, String city, double total) {}

List<Order> orders = List.of(
    new Order("ana", "Pune", 120), new Order("raj", "Delhi", 40),
    new Order("li", "Pune", 75));

Map<String, Double> totalByCity = orders.stream()
    .filter(o -> o.total() > 50)
    .collect(Collectors.groupingBy(Order::city,
        Collectors.summingDouble(Order::total)));  // {Pune=195.0}

Optional<Order> biggest = orders.stream()
    .max(Comparator.comparingDouble(Order::total));
String who = biggest.map(Order::customer).orElse("none");

Refactoring a loop into a stream

The loop builds a sorted list of names of active adult users in upper case. Step 1: each if becomes a filter. Step 2: the value you add becomes a map. Step 3: the sort becomes sorted(). Step 4: the result list becomes toList(). The stream version has no temporary list and reads top to bottom as the rules themselves. Both versions give the same output.

java
record User(String name, boolean active, int age) {}

// Before
List<String> names = new ArrayList<>();
for (User u : users) {
  if (u.active() && u.age() >= 18) names.add(u.name().toUpperCase());
}
Collections.sort(names);

// After
List<String> names2 = users.stream()
    .filter(u -> u.active() && u.age() >= 18)
    .map(u -> u.name().toUpperCase())
    .sorted()
    .toList();

Top 3 most common words

Step 1: split the text into words and stream them. Step 2: groupingBy with counting() builds a Map of word to count. Step 3: stream the map's entries and sort by count, highest first, breaking ties alphabetically so the output is stable. Step 4: limit(3) keeps the top three, and map formats each entry. The result is [the=3, and=2, bat=1].

java
String text = "the cat and the hat and the bat";

Map<String, Long> freq = Arrays.stream(text.split(" "))
    .collect(Collectors.groupingBy(w -> w, Collectors.counting()));

List<String> top = freq.entrySet().stream()
    .sorted(Map.Entry.<String, Long>comparingByValue().reversed()
        .thenComparing(Map.Entry.comparingByKey()))
    .limit(3)
    .map(e -> e.getKey() + "=" + e.getValue())
    .toList();

Quick reference

  • Nothing runs until a terminal operation: collect, toList, count, findFirst, forEach
  • Lambdas can only use local variables that are effectively final
  • toMap throws on duplicate keys unless you pass a merge function
  • groupingBy(key, counting()) gives Map<K, Long>
  • orElse always evaluates its argument; orElseGet only when empty
  • Use mapToInt(...).sum() instead of boxing with reduce(0, Integer::sum)
  • A stream can be used once; call stream() again for a second pass
  • Avoid parallelStream() in web servers unless you have measured a gain

Common mistakes

  • Changing shared variables inside a lambda instead of collecting results.
  • Calling Optional.get() without isPresent, which defeats the purpose.
  • Forcing every loop into a stream when a plain loop is clearer.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does Stream.of(1, 2, 3).peek(System.out::println).filter(x -> x > 1); print?

Question 2

2You call Collectors.toMap(Person::city, Person::name) and two people live in Pune. What happens?

Question 3

3Which method reference matches the lambda s -> s.length()?

Question 4

4Why might user.orElse(loadDefaultUserFromDb()) be wasteful?

Question 5

5A lambda contains total += x, where total is a local int. What happens?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    From List.of(1, 2, 3, 4, 5, 6, 7), produce a list of the squares of the odd numbers.

  2. Exercise 2medium

    Given record Employee(String dept, String name, double salary), build a Map from department to average salary, with departments sorted by name.

  3. Exercise 3hard

    Given record Order(String customer, List<Item> items) and record Item(String name, double price), return the name of the customer who spent the most in total, as an Optional<String>.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Are streams slower than for loops?
For tiny hot loops a plain loop can be a little faster, mostly because of boxing and extra calls. For normal business code the difference is too small to matter, so choose whichever reads better.
What is the difference between map and flatMap?
map turns each element into exactly one new element. flatMap turns each element into a stream of zero or more elements and joins them, for example orders.stream().flatMap(o -> o.items().stream()).
Should I use Optional for fields or parameters?
No. Optional is meant for return values. For parameters use overloads or allow null with clear docs, and for fields use null internally and return Optional from the getter if needed.
When should I use parallel streams?
Only for large CPU-bound work with no shared mutable state, after measuring a real speed-up. In server apps, a separate executor usually gives more control.

Go deeper

ShareXLinkedInWhatsApp