Lesson 9 of 12 · 9 min · Collections, streams and generics
Lambdas, functional interfaces and the Streams API
What you will learn
- Write lambda expressions and method references
- Know the core functional interfaces:
Predicate,Function,Consumer,Supplier - Build stream pipelines with
filter,map,sortedandcollect - Group and summarise with collectors
- Use
Optionaland know when a plain loop is better
In simple words
A lambda is a short piece of behaviour that you can hand to a method, like giving the sorter a one-line rule: "compare by marks". A stream is an assembly line for data: items go in at one end, pass through steps such as "keep only the paid orders" and "take the amount", and come out as a list or a total at the other end. You say what you want, not how to loop.
Words to know
- Lambda: a short anonymous function written as
(a, b) -> a + b. - Functional interface: an interface with exactly one abstract method, which a lambda can implement.
- Stream: a sequence of elements that you process with a pipeline of operations.
- Terminal operation: the final step of a stream that produces a result and runs the pipeline.
Lambdas and method references
A lambda is an implementation of a functional interface:
Runnable r = () -> System.out.println("hello");
Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length());
Syntax: (parameters) -> expression or (parameters) -> { statements; return value; }. Parameter types are inferred. A method reference is a shorthand when the lambda just calls an existing method:
| Form | Example | Same as |
|---|---|---|
| static method | Integer::parseInt |
s -> Integer.parseInt(s) |
| instance method of a given object | System.out::println |
x -> System.out.println(x) |
| instance method of the first parameter | String::toUpperCase |
s -> s.toUpperCase() |
| constructor | ArrayList::new |
() -> new ArrayList<>() |
A lambda can use effectively final local variables from its surroundings (variables you never reassign); it cannot modify local variables. It is not an anonymous inner class: this inside a lambda refers to the enclosing object.
Functional interfaces
Java provides standard ones in java.util.function:
| Interface | Method | Meaning | Example |
|---|---|---|---|
Predicate<T> |
boolean test(T) |
a yes-or-no test | s -> s.isEmpty() |
Function<T, R> |
R apply(T) |
transform a value | Student::name |
Consumer<T> |
void accept(T) |
do something with a value | System.out::println |
Supplier<T> |
T get() |
produce a value | () -> new ArrayList<>() |
UnaryOperator<T> |
T apply(T) |
Function<T, T> |
String::trim |
BinaryOperator<T> |
T apply(T, T) |
combine two values | Integer::sum |
Primitive versions (IntPredicate, ToIntFunction, IntBinaryOperator) avoid boxing. You can compose them: isLong.and(isCapital), f.andThen(g). Annotate your own with @FunctionalInterface so the compiler checks there is one abstract method.
The stream pipeline
A stream pipeline has three parts:
- Source:
list.stream(),Arrays.stream(array),Stream.of(...),IntStream.range(0, 10),Files.lines(path). - Intermediate operations (lazy; they return a stream):
filter,map,sorted,distinct,limit,skip,flatMap,peek. - A terminal operation (starts the work):
collect,toList,forEach,reduce,count,sum,min,max,anyMatch,allMatch,findFirst.
record Order(int id, String customer, String status, double amount) {}
List<Order> orders = List.of(
new Order(101, "Asha", "paid", 1200),
new Order(102, "Asha", "paid", 800),
new Order(103, "Ravi", "refunded", 1500),
new Order(104, "Meena", "paid", 600),
new Order(105, "Meena", "pending", 900),
new Order(106, "Asha", "paid", 500));
double paidTotal = orders.stream()
.filter(o -> o.status().equals("paid"))
.mapToDouble(Order::amount)
.sum(); // 3100.0
List<String> topCustomers = orders.stream()
.filter(o -> o.amount() >= 800)
.map(Order::customer)
.distinct()
.sorted()
.toList(); // [Asha, Meena, Ravi] (Java 16+ toList)
Streams are lazy: nothing runs until the terminal operation, and each element flows through the whole pipeline in turn. A stream can be used once; reusing it throws IllegalStateException. Streams do not modify the source.
Useful operations: map transforms each element; flatMap flattens nested collections (lists.stream().flatMap(List::stream)); mapToInt/mapToDouble give primitive streams with sum(), average() (an OptionalDouble), summaryStatistics(); reduce combines elements (reduce(0.0, Double::sum)); limit(3) after sorted gives the top 3; Java 16 added mapMulti, and Java 9 takeWhile and dropWhile.
Collectors
collect(Collectors...) gathers results:
Map<String, Double> totalByCustomer = orders.stream()
.collect(Collectors.groupingBy(Order::customer, Collectors.summingDouble(Order::amount)));
// {Asha=2500.0, Ravi=1500.0, Meena=1500.0} (map order not guaranteed)
Map<String, Long> countByStatus = orders.stream()
.collect(Collectors.groupingBy(Order::status, Collectors.counting()));
// {paid=4, refunded=1, pending=1}
Map<Boolean, List<Order>> bigAndSmall = orders.stream()
.collect(Collectors.partitioningBy(o -> o.amount() >= 1000));
String names = orders.stream().map(Order::customer).distinct()
.collect(Collectors.joining(", ", "[", "]")); // [Asha, Ravi, Meena]
Map<Integer, Order> byId = orders.stream()
.collect(Collectors.toMap(Order::id, o -> o)); // throws if two keys collide
groupingBy is the stream version of SQL GROUP BY; the second argument is a downstream collector (counting, summingDouble, averagingDouble, mapping, maxBy). toMap throws IllegalStateException on duplicate keys unless you pass a merge function.
Optional
Methods such as findFirst, min, max and reduce (without an initial value) return an Optional<T>: a box that may or may not hold a value, which forces you to deal with "nothing":
Optional<Order> biggest = orders.stream().max(Comparator.comparingDouble(Order::amount));
double amount = biggest.map(Order::amount).orElse(0.0);
biggest.ifPresent(o -> System.out.println(o.customer()));
Avoid Optional.get() without checking; prefer orElse, orElseGet, orElseThrow, map and ifPresent. Use Optional as a return type, not for fields or parameters.
Parallel streams and side effects
parallelStream() splits work across threads and helps only for large data and CPU-heavy, independent, stateless operations; it can be slower or wrong otherwise (shared mutable state, blocking I/O, small lists). Measure before using it. Keep lambdas pure: do not modify outside variables, and do not use peek for logic.
When not to use streams
Use a normal loop when you need to break out early with complex conditions, modify local state, handle checked exceptions per element, or when a stream would be harder to read than three lines of loop. Debugging long pipelines is harder; split them into named steps. Avoid very long chains and nested streams.
Common mistakes
- Reusing a stream after a terminal operation.
- Forgetting the terminal operation, so nothing happens.
- Changing a collection while streaming it.
toMapwith duplicate keys.- Calling
Optional.get()without a check. - Using
forEachto build a list (usecollectortoList). - Parallel streams everywhere.
Try it yourself
- Using the
orderslist, compute the total amount of paid orders and the average amount per customer. - Return the three biggest orders as a list of ids.
- Group order ids by status with
groupingByandmapping. - Rewrite a loop you have with a stream, and say which is clearer.
- Use
Optionalto find the largest order for a given customer, returning "none" if there is no order.
Check yourself
What is a functional interface?
An interface with exactly one abstract method, which can be implemented with a lambda or a method reference, such as Comparator, Runnable and Predicate.
What is the difference between intermediate and terminal operations?
Intermediate operations like filter and map are lazy and return a stream; a terminal operation like collect or sum triggers the pipeline and returns a result.
Why can a stream be used only once?
After the terminal operation the pipeline is consumed; reusing it throws IllegalStateException. Create a new stream from the source.
What does Collectors.groupingBy do?
It groups elements by a classifier function into a map, optionally applying a downstream collector such as counting to each group.
Interview questions
What is the difference between map and flatMap?
map transforms each element into exactly one new element. flatMap transforms each element into a stream and flattens all of them into one stream, which is useful for lists of lists.
Is a stream a collection?
No. A stream does not store elements; it is a view of a source with a pipeline of operations, which are lazy and can be consumed once.
How do you find the second highest salary with streams?
employees.stream().map(Employee::salary).distinct().sorted(Comparator.reverseOrder()).skip(1).findFirst() returns an Optional holding the second highest distinct salary.
Summary
- Lambdas and method references implement functional interfaces; know
Predicate,Function,ConsumerandSupplier. - A stream pipeline is source, lazy intermediate steps and one terminal step; it runs once.
- Collectors such as
groupingBy,partitioningBy,toMapandjoiningsummarise data. - Handle absent results with
Optional; keep lambdas pure and use loops when clearer.
Going deeper
- dev.java: The Stream API: the official guide.
- java.util.stream package documentation: pipelines, laziness and reduction.
- java.util.function package: all the functional interfaces.
- The Java Tutorials: Lambda Expressions: syntax and scope.
See how much of this you can explain
A free mock interview asks you new questions on Core Java: OOP, collections and exceptions for Java Full Stack Developer and scores every answer, with what to fix.