skip to content

What did Java 8 bring that changed how developers write Java code?

level: juniorimportance: must knowfreq 78%

answer

  1. behaviour passed as a value
  2. one abstract method, one lambda
  3. how Collection gained a new method
  4. pipelines instead of loops
  5. immutable dates instead of Calendar

basics

~20 s

Java 8 added lambda expressions, method references and default methods, shipped the Stream API, Optional and CompletableFuture to use them, and added the immutable java.time API. Much everyday code moved from loops and anonymous classes to declarative pipelines.

solid answer

~40 s

Java 8 changed the style of everyday Java. Lambda expressions and method references let you pass behaviour as a value, and a lambda evaluates to an instance of a functional interface. Default methods let the JDK add `stream()` to `Collection` without forcing existing implementers to write it, which made the Stream API possible: `filter`, `map` and `collect` pipelines, serial or parallel, in place of hand-written loops. `Optional` gave methods a return type for "no result", `CompletableFuture` gave composable asynchronous steps, and `java.time` gave immutable alternatives to the mutable `Date` and `Calendar`. Underneath, HotSpot removed the permanent generation, and `HashMap` started using balanced trees under heavy hash collisions.

code

java · 39 lines
java
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class Java8Idioms {
    static class Order {
        final String customer;
        final LocalDate placed;
        final int total;

        Order(String customer, LocalDate placed, int total) {
            this.customer = customer;
            this.placed = placed;
            this.total = total;
        }
    }

    public static void main(String[] args) {
        List<Order> orders = Arrays.asList(
                new Order("ana", LocalDate.of(2026, 1, 5), 120),
                new Order("bo", LocalDate.of(2026, 2, 9), 40),
                new Order("ana", LocalDate.of(2026, 3, 1), 300));

        List<String> bigSpenders = orders.stream()
                .filter(o -> o.total > 100)
                .map(o -> o.customer)
                .distinct()
                .collect(Collectors.toList());

        Optional<Order> latest = orders.stream()
                .max(Comparator.comparing((Order o) -> o.placed));

        System.out.println(bigSpenders);
        System.out.println(latest.map(o -> o.placed.plusDays(1)).orElse(null));
    }
}

go deeper

for a junior

Recall the big four: lambdas, default methods, streams and java.time. Be ready to write a short filter and map pipeline, and to say what it replaces.

for a middle

Explain how the parts depend on each other: functional interfaces give lambdas a type, and default methods let existing collection interfaces gain stream() without forcing implementers to write it.

for a senior

Show judgment about where the features stop paying off, such as parallel streams on small or blocking workloads, or pipelines that hide several exits and are clearer as loops.

for a principal

Treat Java 8 as a lesson in evolving a widely implemented API: default methods made a compatible change possible, and that compatibility constraint still shapes how the platform grows.

## Why Java 8 still comes up Java 8 is the release that changed the style of everyday Java. Before it, passing behaviour meant an anonymous class, and processing a collection meant a loop with a temporary list. After it, both could be a single expression. Interviewers ask about it to see whether you understand that the pieces depend on each other: the library additions rest on the language additions. ```java // Before Java 8 List<String> names = new ArrayList<>(); for (Order o : orders) { if (o.total > 100) { names.add(o.customer); } } // With Java 8 List<String> names = orders.stream() .filter(o -> o.total > 100) .map(o -> o.customer) .collect(Collectors.toList()); ``` ## The language additions JEP 126 delivered these as one package: - **Lambda expressions.** Behaviour written in place, such as `o -> o.total > 100`. Evaluating one produces an instance of a **functional interface**, an interface with a single abstract method. The target type comes from the context, so the same text can become a `Predicate` or an interface of your own. - **Method references.** `String::length` is a compact lambda for a method that already has a name. - **Default methods.** An interface method with a body, inherited by implementers that do not override it. JEP 126 calls them virtual extension methods. - **Enhanced type inference.** Generic calls and lambda parameters need fewer explicit types. It does not reach the receiver of a chained call, so `Comparator.comparing(o -> o.total).reversed()` still needs an explicit parameter type. Default methods are the piece candidates underrate. `Collection` has implementers far outside the JDK. An abstract `stream()` would have stopped every concrete implementer compiling, so `stream()` is a `default` method and they inherit it. A lambda is also not plain shorthand for an anonymous class. Inside a lambda, `this` means the enclosing instance. Inside an anonymous class, it means the anonymous class instance. ## The library additions | Addition | What it gave you | |---|---| | `java.util.stream` | Filter, map and reduce pipelines over collections, serial or parallel, in place of hand-written loops | | `java.util.function` | Standard functional interfaces such as `Function`, `Predicate` and `Supplier` | | `Optional` | A method return type for "no result", in place of a documented `null` | | `CompletableFuture` | Composable asynchronous steps, in place of blocking on `Future.get()` | | `java.time` | Immutable date and time values, in place of mutable `Date` and `Calendar` | | `Map.computeIfAbsent`, `merge`, `getOrDefault` | Common map updates as one call | | `Base64`, `StringJoiner` | Standard classes for small jobs that used to need helper code | Two details are worth saying out loud: - A **stream is not a collection**. It is a pipeline over a source. Nothing runs until a terminal operation such as `collect`, and a stream should be operated on only once. - `Optional` is **primarily intended as a method return type**, says its own documentation. How far to take it is a separate discussion. ## What changed underneath Two runtime changes shipped in the same release: - **The permanent generation is gone** (JEP 122). Class metadata moved to native memory, which removed the need to tune the size of the permanent generation. - **`HashMap` copes better with collisions** (JEP 180). Under heavy hash collisions, `HashMap` and `LinkedHashMap` store entries in balanced trees rather than linked lists. JEP 180 warns that iteration order can change within what the specification allows, so code relying on that order may notice. ## What did not arrive in Java 8 Candidates often blur later releases into this one, and an interviewer will notice: - The module system, `List.of` and `Stream.takeWhile` came in Java 9. - `var` came in Java 10. - `Optional.isEmpty` and `String.isBlank` came in Java 11. - `Stream.toList` came in Java 16, the same release in which records became final. ## How to answer Lead with the dependency, because it shows you understand the design: lambdas plus default methods made the Stream API possible. Then give one concrete thing that changed in code you have written, such as replacing a loop with a pipeline or replacing `Calendar` with `LocalDate`. Finish with a limit if you have one: a stream reads better for a filter and a map, while a plain loop can still be clearer when the logic has several exits or changes local state.

  • Why could the JDK not simply add an abstract stream() method to Collection?
    Every concrete class outside the JDK that implements `Collection` would stop compiling until it implemented the method. Classes already compiled would still link, but calling `stream()` on one would throw `AbstractMethodError`. A default method avoids both: implementers inherit a working body and may override it. The risk left is a clash, since a class that already declared an incompatible `stream()` fails to compile.
  • What happens when a class inherits the same default method from two unrelated interfaces?
    It does not compile: javac reports the two types as incompatible. The class must override the method, and inside the override it can pick one parent explicitly with `First.super.m()`.
  • Why must a local variable used inside a lambda be final or effectively final?
    The language rule is that a local variable used but not declared in a lambda body must be final or effectively final. The lambda may run later or on another thread, so it works from a captured value. Allowing later writes would let the variable and the captured value disagree.

  • Java 8 introduced the module system and the var keyword.
  • A lambda is plain shorthand for an anonymous class, so this means the same in both.
  • A stream stores its elements and can be traversed again like a list.
  • Default methods let an interface keep per-instance state.
  • Calling parallelStream() makes any pipeline faster.
  • java.time types are mutable, so each thread needs its own copy.

Lambda expressions and method references
Java 1.8
Default methods in interfaces
Java 1.8
Stream API
Java 1.8
java.time date and time API
Java 1.8
java.util.Optional
Java 1.8

Assumes JDK 27 as the baseline; the Java 8 features this answer describes are all still in the platform at 27.

context