Tutorials / Java: From Zero to Advanced / Lambdas and the Stream API

Lambdas and the Stream API

16 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. 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.

InterfaceMethodMeaning
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 map or filter make 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.removeIf or forEach is enough.
  • Calling get() on an Optional without checking it. Use orElse or ifPresent.

Try it yourself

  1. Print the names of the products in Furniture with a price below 100.
  2. Compute the total stock per category with Collectors.summingInt.
  3. Find the three cheapest products using sorted and limit.
  4. Turn the list of products into a map from name to price with Collectors.toMap.
java
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