Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

JV
Java
0/14 completed
Beginner
Hello JavaVariables and typesControl flowMethodsArrays and strings
Intermediate
Classes and objectsInheritance and interfacesCollectionsExceptions
Advanced
GenericsLambdas and streamsRecords, enums and pattern matching
Pro
Concurrency and virtual threadsBuild tools, testing and real projects
Tracks / Java / Advanced

Lambdas and streams

Java 8 brought functional programming to Java: lambdas let you pass behaviour around as a value, and streams let you process collections declaratively ("filter these, map those, sum the result") instead of writing loops by hand. Modern Java code uses them everywhere.

Lambdas

A lambda is a short, anonymous function: parameters -> expression.

java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Priya", "asha", "Rahul", "li"));

        names.sort((a, b) -> a.compareToIgnoreCase(b));
        System.out.println(names);

        names.sort((a, b) -> Integer.compare(a.length(), b.length()));
        System.out.println(names);

        names.forEach(n -> System.out.print(n.toUpperCase() + " "));
        System.out.println();

        names.removeIf(n -> n.length() < 3);
        System.out.println(names);

        String[] arr = {"kiwi", "fig", "banana"};
        Arrays.sort(arr, (a, b) -> b.length() - a.length());
        System.out.println(Arrays.toString(arr));
    }
}
Output
[asha, li, Priya, Rahul]
[li, asha, Priya, Rahul]
LI ASHA PRIYA RAHUL 
[asha, Priya, Rahul]
[banana, kiwi, fig]

Lambda syntax:

java
x -> x * 2                       // one parameter, one expression
(a, b) -> a + b                  // two parameters
() -> System.out.println("hi")   // no parameters
(String s) -> {                  // explicit types and a block body
    String t = s.trim();
    return t.isEmpty() ? "?" : t;
}

Functional interfaces

A lambda can be used wherever an interface with exactly one abstract method is expected (a functional interface). The java.util.function package defines the common ones:

Interface Takes → returns Example
Predicate<T> T → boolean s -> s.isEmpty()
Function<T, R> T → R s -> s.length()
Consumer<T> T → nothing s -> System.out.println(s)
Supplier<T> nothing → T () -> new ArrayList<>()
BiFunction<T, U, R> T, U → R (a, b) -> a + b
UnaryOperator<T> T → T s -> s.toUpperCase()
java
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {
        Predicate<String> isLong = s -> s.length() > 5;
        Function<Integer, Integer> square = n -> n * n;
        Function<Integer, Integer> plusOne = n -> n + 1;
        Supplier<String> greeting = () -> "Hello!";

        System.out.println(isLong.test("Java") + " " + isLong.test("Programming"));
        System.out.println(square.apply(7));
        System.out.println(square.andThen(plusOne).apply(7));    // (7*7)+1
        System.out.println(isLong.negate().test("Java"));
        System.out.println(greeting.get());
    }
}
Output
false true
49
50
true
Hello!

Method references

When a lambda just calls an existing method, a method reference is shorter: ClassName::method.

java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> words = List.of("stream", "lambda", "java");

        words.forEach(System.out::println);                          // s -> System.out.println(s)
        System.out.println(words.stream().map(String::toUpperCase).toList());   // s -> s.toUpperCase()
        System.out.println(words.stream().map(String::length).toList());
    }
}
Output
stream
lambda
java
[STREAM, LAMBDA, JAVA]
[6, 6, 4]

Streams

A stream is a pipeline of operations over a sequence of elements:

source  →  intermediate operations (filter, map, sorted…)  →  terminal operation (toList, sum, count…)
java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(5, 3, 8, 1, 9, 2, 7);

        List<Integer> result = numbers.stream()
                .filter(n -> n % 2 == 1)        // keep odd numbers
                .map(n -> n * n)                // square them
                .sorted()                       // ascending
                .toList();                      // collect into a List
        System.out.println(result);

        int sum = numbers.stream().mapToInt(Integer::intValue).sum();
        long big = numbers.stream().filter(n -> n > 4).count();
        System.out.println(sum + " " + big);
        System.out.println(numbers.stream().anyMatch(n -> n > 8) + " " + numbers.stream().allMatch(n -> n > 0));
    }
}
Output
[1, 9, 25, 49, 81]
35 4
true true

Streams are lazy: nothing happens until the terminal operation runs. They also don't change the original collection.

Working with objects

Here's where streams shine. Using a record (a compact data class; the next lesson covers them):

java
import java.util.Comparator;
import java.util.List;

public class Main {
    record Product(String name, String category, double price, int stock) {}

    public static void main(String[] args) {
        List<Product> products = List.of(
            new Product("Laptop", "Electronics", 899, 15),
            new Product("Headphones", "Electronics", 59.99, 80),
            new Product("Mug", "Kitchen", 8.99, 200),
            new Product("Lamp", "Home", 29, 0),
            new Product("Keyboard", "Electronics", 45.5, 40));

        // names of in-stock electronics, cheapest first
        List<String> names = products.stream()
                .filter(p -> p.category().equals("Electronics"))
                .filter(p -> p.stock() > 0)
                .sorted(Comparator.comparingDouble(Product::price))
                .map(Product::name)
                .toList();
        System.out.println(names);

        double stockValue = products.stream().mapToDouble(p -> p.price() * p.stock()).sum();
        System.out.printf("Stock value: %.2f%n", stockValue);

        Product priciest = products.stream().max(Comparator.comparingDouble(Product::price)).orElseThrow();
        System.out.println("Most expensive: " + priciest.name());

        System.out.println(products.stream()
                .sorted(Comparator.comparing(Product::category).thenComparing(Product::name))
                .map(p -> p.category() + "/" + p.name())
                .toList());
    }
}
Output
[Keyboard, Headphones, Laptop]
Stock value: 21902.20
Most expensive: Laptop
[Electronics/Headphones, Electronics/Keyboard, Electronics/Laptop, Home/Lamp, Kitchen/Mug]

Comparator.comparing(...) builds sort orders from method references, and thenComparing breaks ties.

Collectors: grouping and summarising

java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
    record Order(String customer, String city, double total) {}

    public static void main(String[] args) {
        List<Order> orders = List.of(
            new Order("Asha", "Bengaluru", 1018.98),
            new Order("Rahul", "Mumbai", 35.96),
            new Order("Fatima", "Mumbai", 120.00),
            new Order("Asha", "Bengaluru", 42.00),
            new Order("Li", "Singapore", 1827.00));

        Map<String, Long> ordersPerCity = orders.stream()
                .collect(Collectors.groupingBy(Order::city, TreeMap::new, Collectors.counting()));
        System.out.println(ordersPerCity);

        Map<String, Double> spendPerCustomer = orders.stream()
                .collect(Collectors.groupingBy(Order::customer, TreeMap::new, Collectors.summingDouble(Order::total)));
        System.out.println(spendPerCustomer);

        String customers = orders.stream().map(Order::customer).distinct().sorted()
                .collect(Collectors.joining(", ", "[", "]"));
        System.out.println(customers);

        Map<Boolean, List<String>> bigOrders = orders.stream()
                .collect(Collectors.partitioningBy(o -> o.total() > 100,
                         Collectors.mapping(Order::customer, Collectors.toList())));
        System.out.println(bigOrders);
    }
}
Output
{Bengaluru=2, Mumbai=2, Singapore=1}
{Asha=1060.98, Fatima=120.0, Li=1827.0, Rahul=35.96}
[Asha, Fatima, Li, Rahul]
{false=[Rahul, Asha], true=[Asha, Fatima, Li]}

Optional: an explicit "maybe"

Methods like findFirst() and max() return an Optional: a box that may or may not contain a value. It forces you to handle the "nothing found" case instead of getting a surprise null:

java
import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        List<String> emails = List.of("asha@example.com", "rahul@test.org");

        Optional<String> gmail = emails.stream().filter(e -> e.endsWith("@gmail.com")).findFirst();
        System.out.println(gmail.isPresent());
        System.out.println(gmail.orElse("no gmail address"));

        String domain = emails.stream().findFirst()
                .map(e -> e.substring(e.indexOf('@') + 1))
                .orElse("unknown");
        System.out.println(domain);
    }
}
Output
false
no gmail address
example.com

Streams vs loops

Streams are great for transforming and summarising data in a readable pipeline. Plain loops are still fine, and often clearer, when you need early exits, complex state, or checked exceptions inside the loop body. Choose whichever reads better.

Practice

Using the Product list above:

  1. Print the names of all products under 50, in upper case, sorted alphabetically.
  2. Calculate the average price per category (Collectors.averagingDouble).
  3. Find whether any product is out of stock, and print its name using Optional.
✎ Check your understanding

1.What is a functional interface?

2.When does a stream pipeline actually process the elements?

3.What does String::toUpperCase mean in .map(String::toUpperCase)?

← Generics