Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › Java

Java 8 Features — Lambdas and Streams

Java 8 (2014) added a functional style to Java. These features are asked in almost every Java interview.

Lambda expressions

A short way to write an anonymous function.

// before
Comparator<String> byLen = new Comparator<String>() {
    public int compare(String a, String b) { return a.length() - b.length(); }
};
// Java 8
Comparator<String> byLen2 = (a, b) -> a.length() - b.length();
names.sort(byLen2);

Syntax: (params) -> expression or (params) -> { statements; }.

Functional interfaces

An interface with exactly one abstract method — a lambda implements it. Mark it with @FunctionalInterface.

Interface Method Example
Predicate<T> boolean test(T) x -> x > 0
Function<T,R> R apply(T) s -> s.length()
Consumer<T> void accept(T) s -> System.out.println(s)
Supplier<T> T get() () -> new ArrayList<>()
BiFunction<T,U,R> R apply(T,U) (a, b) -> a + b
Runnable, Comparator existing interfaces that also work

Method references

Shorter lambdas that just call a method.

names.forEach(System.out::println);          // s -> System.out.println(s)
list.stream().map(String::toUpperCase);      // s -> s.toUpperCase()
Supplier<List<String>> make = ArrayList::new;

Stream API

A stream is a pipeline of operations on a collection: source → intermediate operations → one terminal operation. Streams don't change the source and are lazy (nothing runs until the terminal operation).

List<Integer> nums = List.of(5, 2, 8, 1, 9, 2);

List<Integer> result = nums.stream()
        .filter(n -> n > 2)          // 5, 8, 9
        .map(n -> n * 10)            // 50, 80, 90
        .sorted()                    // 50, 80, 90
        .collect(Collectors.toList());

int sum = nums.stream().mapToInt(Integer::intValue).sum();              // 27
long evens = nums.stream().filter(n -> n % 2 == 0).count();             // 3
Optional<Integer> max = nums.stream().max(Integer::compare);            // 9
List<Integer> unique = nums.stream().distinct().toList();               // Java 16+: toList()
Intermediate (return a stream) Terminal (end the stream)
filter, map, flatMap, sorted, distinct, limit, skip, peek collect, forEach, reduce, count, min, max, anyMatch, allMatch, findFirst

Grouping and counting

// students grouped by department
Map<String, List<Student>> byDept = students.stream()
        .collect(Collectors.groupingBy(Student::getDept));

// word frequency
Map<String, Long> freq = words.stream()
        .collect(Collectors.groupingBy(w -> w, Collectors.counting()));

// join names
String csv = students.stream().map(Student::getName).collect(Collectors.joining(", "));

reduce

int product = nums.stream().reduce(1, (a, b) -> a * b);

Optional

A box that may or may not hold a value — a clear alternative to returning null.

Optional<User> u = repo.findByEmail(email);
String name = u.map(User::getName).orElse("Guest");
u.ifPresent(x -> System.out.println(x.getName()));
User must = u.orElseThrow(() -> new NotFoundException("No user"));

Default and static methods in interfaces

interface Shape {
    double area();
    default String describe() { return "Area: " + area(); }   // has a body
    static Shape unit() { return () -> 1.0; }
}

Lets old interfaces gain new methods without breaking existing classes.

Other Java 8 additions

Interview one-liners

More Java notes