Streams & Lambdas

Functional programming in Java — lambdas, functional interfaces, method references, the Stream API (map, filter, reduce, collect, groupingBy), laziness, parallel streams, and Optional.

Intermediate 3 min readLesson 6 of 14 Interview Q&A

Java 8 added lambdas (anonymous functions) and the Stream API (declarative pipelines over collections). Together they replace many verbose loops with readable transformations.

Lambdas and functional interfaces

A lambda is a concise implementation of a functional interface — an interface with exactly one abstract method.

Java
// Before: anonymous class
Comparator<String> byLength = new Comparator<>() {
    public int compare(String a, String b) { return Integer.compare(a.length(), b.length()); }
};

// Lambda
Comparator<String> byLength2 = (a, b) -> Integer.compare(a.length(), b.length());

// Even better: a comparator factory with a method reference
Comparator<String> byLength3 = Comparator.comparingInt(String::length);

The core functional interfaces (java.util.function)

InterfaceSignatureExample
Function<T, R>R apply(T)String::length
BiFunction<T, U, R>R apply(T, U)(a, b) -> a + b
Predicate<T>boolean test(T)s -> s.isEmpty()
Consumer<T>void accept(T)System.out::println
Supplier<T>T get()ArrayList::new
UnaryOperator<T> / BinaryOperator<T>T apply(T) / T apply(T, T)String::trim, Integer::sum
Primitive versionsIntFunction, ToIntFunction, IntPredicate…Avoid boxing

Functions compose: f.andThen(g), f.compose(g), p.and(q), p.negate(), comparator.thenComparing(...).

Method references

KindSyntaxEquivalent lambda
Static methodInteger::parseInts -> Integer.parseInt(s)
Instance method of a particular objectSystem.out::printlnx -> System.out.println(x)
Instance method of an arbitrary objectString::toUpperCases -> s.toUpperCase()
ConstructorArrayList::new() -> new ArrayList<>()

Capturing variables

Lambdas can use local variables only if they're effectively final (never reassigned). This avoids data races on stack variables. To accumulate, use streams' reductions or an AtomicInteger, not a captured counter.

The Stream API

A stream is a pipeline: a source, zero or more intermediate operations (lazy, return a new stream) and one terminal operation (triggers processing and produces a result).

orders.stream()sourcefilter(paid)intermediatemap(total)intermediatesum()terminal
Java
record Order(String customer, String status, long totalCents, List<String> items) {}

long paidRevenue = orders.stream()
        .filter(o -> o.status().equals("PAID"))
        .mapToLong(Order::totalCents)
        .sum();

List<String> topCustomers = orders.stream()
        .sorted(Comparator.comparingLong(Order::totalCents).reversed())
        .map(Order::customer)
        .distinct()
        .limit(3)
        .toList();                                    // Java 16+: unmodifiable list

List<String> allItems = orders.stream()
        .flatMap(o -> o.items().stream())             // one-to-many
        .toList();

boolean anyLarge = orders.stream().anyMatch(o -> o.totalCents() > 100_000);
Optional<Order> first = orders.stream().filter(o -> o.status().equals("NEW")).findFirst();

Common operations

IntermediateTerminal
filter, map, flatMap, mapToIntcollect, toList, forEach
distinct, sorted, limit, skipreduce, count, sum, min, max, average
peek (debugging), takeWhile, dropWhileanyMatch, allMatch, noneMatch
boxed, mapMultifindFirst, findAny, toArray

Collectors

Java
import static java.util.stream.Collectors.*;

Map<String, List<Order>> byCustomer = orders.stream().collect(groupingBy(Order::customer));

Map<String, Long> revenueByCustomer = orders.stream()
        .collect(groupingBy(Order::customer, summingLong(Order::totalCents)));

Map<String, Long> countByStatus = orders.stream()
        .collect(groupingBy(Order::status, TreeMap::new, counting()));   // sorted map

Map<Boolean, List<Order>> bigAndSmall = orders.stream()
        .collect(partitioningBy(o -> o.totalCents() > 10_000));

Map<String, Order> byId = orders.stream()
        .collect(toMap(Order::customer, o -> o, (a, b) -> a));   // merge fn handles duplicate keys

String csv = names.stream().collect(joining(", ", "[", "]"));
LongSummaryStatistics stats = orders.stream().collect(summarizingLong(Order::totalCents));

Laziness and short-circuiting

Nothing happens until the terminal operation runs. Elements then flow through the pipeline one at a time (vertically), not stage by stage:

Java
Stream.of("a", "bb", "ccc", "dddd")
      .filter(s -> { System.out.println("filter " + s); return s.length() > 1; })
      .map(s -> { System.out.println("map " + s); return s.toUpperCase(); })
      .findFirst();
// filter a, filter bb, map bb  — then stops: "ccc" and "dddd" are never touched

This allows infinite streams (Stream.iterate, Stream.generate) with limit or takeWhile.

Rules and pitfalls

  • A stream can be consumed only once.
  • Operations must be non-interfering (don't modify the source) and preferably stateless and side-effect-free. Don't forEach(list::add) into an external list — collect instead.
  • Use primitive streams (IntStream, mapToLong) to avoid boxing in hot paths.
  • Debugging long chains is harder; keep them short and well named. A plain loop is fine when clearer.
  • Checked exceptions don't fit lambdas; wrap them or use a helper.

Parallel streams

.parallel() splits work across the common ForkJoinPool. It can help for large, CPU-bound, independent workloads over splittable sources (arrays, ArrayList, ranges). It often hurts for small data, I/O-bound work (blocks the shared pool), LinkedList/iterator sources, or operations requiring order (findFirst, sorted, limit). Measure before using it.

Optional

Java
Optional<User> user = repo.findById(id);

String city = user.map(User::address)
                  .map(Address::city)
                  .filter(c -> !c.isBlank())
                  .orElse("Unknown");

user.ifPresentOrElse(this::greet, () -> log.info("no user"));
User u = user.orElseThrow();                 // NoSuchElementException if empty
User v = user.orElseGet(this::createGuest);  // lazily computed fallback (orElse always evaluates its argument)

Avoid optional.get() without checking, Optional fields or parameters, and Optional<List<T>> (return an empty list).

Key takeaways
  • Lambdas implement functional interfaces; method references are shorthand for simple lambdas.
  • Streams: source → lazy intermediate operations → one terminal operation.
  • Collectors (groupingBy, partitioningBy, toMap, joining) replace most aggregation loops.
  • Streams are single-use, lazy and short-circuiting; keep operations side-effect free.
  • Parallel streams only for large CPU-bound work — measure.
  • Optional models absence in return values; chain map/filter/orElse.
Interview questions
QWhat is the difference between map and flatMap?easy

map transforms each element into exactly one element (Stream of T to Stream of R). flatMap transforms each element into a stream and flattens all those streams into one, so one input can yield zero or many outputs — for example, turning a stream of orders into a stream of all their items.

QWhy are streams lazy and why does it matter?medium

Intermediate operations only build the pipeline; work happens when a terminal operation pulls elements through it one at a time. This enables short-circuiting (findFirst stops early), fusing operations into a single pass, and working with infinite streams, and it avoids building intermediate collections.