Lambdas and the Stream API
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
Passing behaviour
A lambda expression is a short anonymous function. It lets you pass a piece of behaviour to a method, such as "sort by this rule" or "run this when done". Before Java 8, you needed an anonymous class with several lines. Now it is a single expression: name -> name.length().
A lambda needs a target type, which is a functional interface: an interface with exactly one abstract method. The package java.util.function provides the common ones.
| Interface | Method | Meaning |
|---|---|---|
Predicate<T> | boolean test(T) | a yes-or-no question |
Function<T, R> | R apply(T) | convert T to R |
Consumer<T> | void accept(T) | do something with T |
Supplier<T> | T get() | produce a T |
BinaryOperator<T> | T apply(T, T) | combine two Ts |
Streams
A stream is a pipeline for processing a sequence of elements. You start from a source such as a list, add intermediate operations like filter and map, and finish with a terminal operation like collect or count. Streams are lazy: nothing happens until the terminal operation runs. A stream can be used only once, and it does not change the source collection.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Main {
record Product(String name, String category, double price, int stock) {}
public static void main(String[] args) {
// Lambdas and functional interfaces
Predicate<String> isLong = s -> s.length() > 4;
Function<String, Integer> length = String::length; // method reference
Supplier<List<String>> newList = ArrayList::new;
BinaryOperator<Integer> add = Integer::sum;
System.out.println(isLong.test("lambda") + " " + length.apply("java") + " " + add.apply(2, 3));
System.out.println(isLong.negate().test("lambda") + " " + newList.get());
List<Product> products = List.of(
new Product("Laptop", "Electronics", 950.0, 5),
new Product("Phone", "Electronics", 600.0, 0),
new Product("Desk", "Furniture", 220.0, 8),
new Product("Chair", "Furniture", 90.0, 20),
new Product("Notebook", "Stationery", 3.5, 300),
new Product("Pen", "Stationery", 1.2, 500));
// filter + map + sorted + toList
List<String> available = products.stream()
.filter(p -> p.stock() > 0)
.filter(p -> p.price() > 50)
.sorted(Comparator.comparingDouble(Product::price).reversed())
.map(Product::name)
.toList();
System.out.println(available);
// Numeric aggregates
double totalValue = products.stream().mapToDouble(p -> p.price() * p.stock()).sum();
System.out.printf("Stock value: %.2f%n", totalValue);
OptionalDouble avg = products.stream().mapToDouble(Product::price).average();
System.out.println("Average price: " + avg.orElse(0));
System.out.println(products.stream().mapToInt(Product::stock).summaryStatistics());
// Grouping
Map<String, List<String>> namesByCategory = products.stream()
.collect(Collectors.groupingBy(Product::category,
TreeMap::new,
Collectors.mapping(Product::name, Collectors.toList())));
System.out.println(namesByCategory);
Map<String, Long> countByCategory = products.stream()
.collect(Collectors.groupingBy(Product::category, TreeMap::new, Collectors.counting()));
System.out.println(countByCategory);
Map<Boolean, List<String>> cheapOrNot = products.stream()
.collect(Collectors.partitioningBy(p -> p.price() < 100,
Collectors.mapping(Product::name, Collectors.toList())));
System.out.println(cheapOrNot);
// Joining text
String csv = products.stream().map(Product::name).collect(Collectors.joining(", ", "[", "]"));
System.out.println(csv);
// Finding things
Optional<Product> priciest = products.stream().max(Comparator.comparingDouble(Product::price));
System.out.println(priciest.map(Product::name).orElse("none"));
System.out.println(products.stream().anyMatch(p -> p.stock() == 0));
// reduce, ranges, flatMap, distinct
int sum = IntStream.rangeClosed(1, 100).sum();
int product = Stream.of(1, 2, 3, 4).reduce(1, (a, b) -> a * b);
System.out.println(sum + " " + product);
List<String> words = Stream.of("a b", "b c", "d")
.flatMap(s -> Arrays.stream(s.split(" ")))
.distinct()
.toList();
System.out.println(words);
// Streams are lazy
Stream<Integer> lazy = Stream.of(1, 2, 3, 4, 5, 6)
.peek(n -> System.out.print("visit " + n + "; "))
.filter(n -> n % 2 == 0);
System.out.println("nothing printed yet");
System.out.println(lazy.limit(2).toList());
}
}
Walking through it
The first block creates functional objects with lambdas and method references. String::length is shorthand for s -> s.length(). There are four kinds of method reference: a static method, a method on a particular object, a method on any object of a type, and a constructor like ArrayList::new. Use a method reference when it is shorter and clearer than a lambda, and a lambda otherwise.
The main pipeline reads like a sentence. Keep products in stock and above 50, sort by price descending, take the names, make a list. Stream.toList(), added in Java 16, returns an unmodifiable list. In older code you will see collect(Collectors.toList()).
For numbers, use the primitive streams: mapToDouble, mapToInt. They avoid boxing and provide sum, average and summaryStatistics. The average returns an OptionalDouble, because an empty stream has no average. We cover Optional in the next lesson.
Collectors.groupingBy is the stream version of SQL's GROUP BY. The simplest form takes a key function and gives a map from key to list. The second argument TreeMap::new picks a sorted map so the output is stable. A downstream collector, such as counting() or mapping(...), decides what to do with each group. partitioningBy splits the elements into two groups using a predicate.
The last block shows laziness. The peek calls print as elements pass through. Nothing is printed before the terminal operation runs, which you can see from the "nothing printed yet" line. When limit(2) has collected two even numbers, the stream stops, so elements 5 and 6 are never visited. Operations are applied element by element through the whole pipeline, not stage by stage.
Good habits
- Keep lambdas short. If one needs more than three lines, give it a name as a method and use a method reference.
- Do not change outside state from inside a stream. Side effects in
maporfiltermake code hard to follow, and they break with parallel streams. - Do not add
.parallel()without measuring. It helps only for large, CPU-bound work and often makes small jobs slower. - A plain loop is sometimes clearer. Use streams where the pipeline reads naturally.
Common mistakes
- Reusing a stream. A second use throws
IllegalStateException. - Forgetting the terminal operation, so nothing runs.
- Modifying the source list while streaming it.
- Using a stream where
list.removeIforforEachis enough. - Calling
get()on an Optional without checking it. UseorElseorifPresent.
Try it yourself
- Print the names of the products in Furniture with a price below 100.
- Compute the total stock per category with
Collectors.summingInt. - Find the three cheapest products using
sortedandlimit. - Turn the list of products into a map from name to price with
Collectors.toMap.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Main {
record Product(String name, String category, double price, int stock) {}
public static void main(String[] args) {
// Lambdas and functional interfaces
Predicate<String> isLong = s -> s.length() > 4;
Function<String, Integer> length = String::length; // method reference
Supplier<List<String>> newList = ArrayList::new;
BinaryOperator<Integer> add = Integer::sum;
System.out.println(isLong.test("lambda") + " " + length.apply("java") + " " + add.apply(2, 3));
System.out.println(isLong.negate().test("lambda") + " " + newList.get());
List<Product> products = List.of(
new Product("Laptop", "Electronics", 950.0, 5),
new Product("Phone", "Electronics", 600.0, 0),
new Product("Desk", "Furniture", 220.0, 8),
new Product("Chair", "Furniture", 90.0, 20),
new Product("Notebook", "Stationery", 3.5, 300),
new Product("Pen", "Stationery", 1.2, 500));
// filter + map + sorted + toList
List<String> available = products.stream()
.filter(p -> p.stock() > 0)
.filter(p -> p.price() > 50)
.sorted(Comparator.comparingDouble(Product::price).reversed())
.map(Product::name)
.toList();
System.out.println(available);
// Numeric aggregates
double totalValue = products.stream().mapToDouble(p -> p.price() * p.stock()).sum();
System.out.printf("Stock value: %.2f%n", totalValue);
OptionalDouble avg = products.stream().mapToDouble(Product::price).average();
System.out.println("Average price: " + avg.orElse(0));
System.out.println(products.stream().mapToInt(Product::stock).summaryStatistics());
// Grouping
Map<String, List<String>> namesByCategory = products.stream()
.collect(Collectors.groupingBy(Product::category,
TreeMap::new,
Collectors.mapping(Product::name, Collectors.toList())));
System.out.println(namesByCategory);
Map<String, Long> countByCategory = products.stream()
.collect(Collectors.groupingBy(Product::category, TreeMap::new, Collectors.counting()));
System.out.println(countByCategory);
Map<Boolean, List<String>> cheapOrNot = products.stream()
.collect(Collectors.partitioningBy(p -> p.price() < 100,
Collectors.mapping(Product::name, Collectors.toList())));
System.out.println(cheapOrNot);
// Joining text
String csv = products.stream().map(Product::name).collect(Collectors.joining(", ", "[", "]"));
System.out.println(csv);
// Finding things
Optional<Product> priciest = products.stream().max(Comparator.comparingDouble(Product::price));
System.out.println(priciest.map(Product::name).orElse("none"));
System.out.println(products.stream().anyMatch(p -> p.stock() == 0));
// reduce, ranges, flatMap, distinct
int sum = IntStream.rangeClosed(1, 100).sum();
int product = Stream.of(1, 2, 3, 4).reduce(1, (a, b) -> a * b);
System.out.println(sum + " " + product);
List<String> words = Stream.of("a b", "b c", "d")
.flatMap(s -> Arrays.stream(s.split(" ")))
.distinct()
.toList();
System.out.println(words);
// Streams are lazy
Stream<Integer> lazy = Stream.of(1, 2, 3, 4, 5, 6)
.peek(n -> System.out.print("visit " + n + "; "))
.filter(n -> n % 2 == 0);
System.out.println("nothing printed yet");
System.out.println(lazy.limit(2).toList());
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account