Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 17 of 20 · 5 min read

Java lambdas and the Stream API

Java lambdas and streams notes with examples: lambda syntax, functional interfaces, method references, filter, map, reduce, collect, groupingBy, Optional.

Lambdas

A lambda is a short, unnamed function you can pass around like a value. It is mainly used to implement a functional interface: an interface with one abstract method.

// before Java 8: an anonymous class
Runnable r1 = new Runnable() {
    @Override
    public void run() { System.out.println("Hello"); }
};

// with a lambda
Runnable r2 = () -> System.out.println("Hello");

Syntax

() -> 42                          // no parameters
x -> x * x                        // one parameter: brackets optional
(a, b) -> a + b                   // two parameters
(String s) -> s.length()          // with a type
(a, b) -> {                       // a block body needs return
    int sum = a + b;
    return sum * 2;
}

A lambda may use local variables from the surrounding code only if they are effectively final (never changed after being set).

Built-in functional interfaces

java.util.function has ready-made interfaces, so you rarely write your own:

InterfaceMethodTakes, givesExample
Predicate<T>testT, booleann -> n > 40
Function<T,R>applyT, Rs -> s.length()
Consumer<T>acceptT, nothings -> System.out.println(s)
Supplier<T>getnothing, T() -> new ArrayList<>()
BinaryOperator<T>applyT and T, T(a, b) -> a + b
import java.util.function.*;

Predicate<Integer> pass = m -> m >= 40;
Function<String, Integer> len = String::length;
System.out.println(pass.test(35));      // false
System.out.println(len.apply("Java"));  // 4

Method references

When a lambda only calls one existing method, a method reference is shorter:

LambdaMethod reference
s -> System.out.println(s)System.out::println
s -> s.toUpperCase()String::toUpperCase
s -> Integer.parseInt(s)Integer::parseInt
() -> new ArrayList<>()ArrayList::new

The Stream API

A stream is a pipeline that takes data from a source (a list, an array, a file), passes it through steps, and produces a result. It does not change the original collection.

import java.util.*;
import java.util.stream.*;

List<Integer> marks = List.of(72, 35, 91, 58, 40, 88);

List<Integer> passed = marks.stream()
        .filter(m -> m >= 40)          // keep
        .sorted()                      // order
        .collect(Collectors.toList()); // gather
System.out.println(passed);            // [40, 58, 72, 88, 91]

A pipeline has three parts:

  1. A source: list.stream(), Arrays.stream(array), Stream.of(...), IntStream.range(1, 11).
  2. Intermediate operations, which return a new stream and run lazily: filter, map, sorted, distinct, limit, skip.
  3. One terminal operation, which produces the result and runs the whole pipeline: collect, forEach, count, reduce, sum, anyMatch, findFirst.

A stream can be used once. Make a new one for each pipeline.

Common operations

List<String> names = List.of("asha", "ravi", "meena", "ravi");

names.stream().map(String::toUpperCase).toList();        // [ASHA, RAVI, MEENA, RAVI]
names.stream().distinct().count();                       // 3
names.stream().filter(n -> n.startsWith("m")).findFirst(); // Optional[meena]
names.stream().anyMatch(n -> n.length() > 4);            // true
names.stream().sorted(Comparator.reverseOrder()).limit(2).toList();   // [ravi, ravi]

toList() is Java 16+. On older versions use collect(Collectors.toList()).

Numbers: sum, average, max

int total = marks.stream().mapToInt(Integer::intValue).sum();          // 384
double avg = marks.stream().mapToInt(Integer::intValue).average().orElse(0);
int top = marks.stream().max(Integer::compare).get();                  // 91
int product = IntStream.rangeClosed(1, 5).reduce(1, (a, b) -> a * b);  // 120

Collectors

record Student(String name, String city, int marks) { }

List<Student> students = List.of(
    new Student("Asha", "Ranchi", 91),
    new Student("Ravi", "Patna", 76),
    new Student("Meena", "Ranchi", 64));

Map<String, List<Student>> byCity =
    students.stream().collect(Collectors.groupingBy(Student::city));

Map<String, Double> avgByCity = students.stream()
    .collect(Collectors.groupingBy(Student::city, Collectors.averagingInt(Student::marks)));
// {Ranchi=77.5, Patna=76.0} (a HashMap: order not guaranteed)

String csv = students.stream().map(Student::name).collect(Collectors.joining(", "));
// Asha, Ravi, Meena

Map<Boolean, List<Student>> split =
    students.stream().collect(Collectors.partitioningBy(s -> s.marks() >= 75));

Optional

Optional<T> is a box that may or may not hold a value. Operations such as findFirst and max return one, so you deal with "no result" deliberately instead of getting null:

Optional<String> first = names.stream().filter(n -> n.startsWith("z")).findFirst();
System.out.println(first.isPresent());          // false
System.out.println(first.orElse("nobody"));     // nobody
first.ifPresent(System.out::println);           // prints nothing

Loop or stream?

Streams suit data transformations: filter, map, group, total. A plain loop is clearer when you need indexes, early exits with complex logic, or to change several variables. Both are correct Java; pick the more readable one.

Common mistakes

  • Reusing a stream after a terminal operation: IllegalStateException.
  • Forgetting the terminal operation, so nothing runs.
  • Changing a local variable inside a lambda (it must be effectively final).
  • Calling get() on an empty Optional: NoSuchElementException. Use orElse or ifPresent.
  • Using forEach to add to another list instead of collect or toList.

Key points

  • A lambda (params) -> body implements a functional interface.
  • Predicate, Function, Consumer, Supplier cover most needs; method references (Class::method) shorten simple lambdas.
  • Stream = source, then lazy intermediate steps, then one terminal step.
  • filter, map, sorted, distinct, limit, then collect, toList, count, sum, reduce.
  • Collectors.groupingBy, joining and partitioningBy build maps and strings.
  • Optional makes "maybe no value" explicit.

Practice questions

1. Write a lambda Predicate<String> that is true for strings longer than 5 characters.
Predicate<String> longWord = s -> s.length() > 5;
2. From List<Integer> nums, make a list of the squares of the even numbers.
List<Integer> sq = nums.stream()
        .filter(n -> n % 2 == 0)
        .map(n -> n * n)
        .toList();
3. What is printed? System.out.println(Stream.of(3, 1, 2).sorted().map(n -> n * 10).toList());

[10, 20, 30].

4. Count the words longer than 3 letters in List<String> words.
long n = words.stream().filter(w -> w.length() > 3).count();
5. Group List<String> words by their first letter.
Map<Character, List<String>> byLetter =
    words.stream().collect(Collectors.groupingBy(w -> w.charAt(0)));