Skip to content
Happy Programming Guide
Start learning
Java

Java 8 Features That Changed the Language

Lambdas, streams, Optional, the new date API and default methods — what Java 8 added, why it mattered, and what has improved since.

A close-up of a computer keyboard

Java 8 was the release that changed how Java is written. Lambdas made functions passable as values, streams replaced a great deal of loop writing, Optional gave null a name, and a new date and time API finally replaced one that had been criticised since the 1990s. Everything since has built on those foundations.

Lambdas#

Before Java 8, passing behaviour meant an anonymous class:

JAVA
Collections.sort(people, new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
});
JAVA
people.sort((a, b) -> a.getName().compareTo(b.getName()));

// Or, more clearly still
people.sort(Comparator.comparing(Person::getName));

Five lines become one. A lambda works anywhere a functional interface is expected — an interface with exactly one abstract method.

JAVA
Runnable task = () -> System.out.println("running");
Function<String, Integer> length = String::length;
Predicate<String> isEmpty = String::isEmpty;
Supplier<List<String>> factory = ArrayList::new;
Consumer<String> printer = System.out::println;
BiFunction<Integer, Integer, Integer> add = Integer::sum;

The double colon is a method reference — shorthand for a lambda that does nothing but call one method. String::length means the same as s -> s.length().

Streams#

JAVA
// Before
List<String> result = new ArrayList<>();
for (Person p : people) {
    if (p.getAge() >= 18) {
        result.add(p.getName().toUpperCase());
    }
}
Collections.sort(result);
JAVA
// After
List<String> result = people.stream()
    .filter(p -> p.getAge() >= 18)
    .map(p -> p.getName().toUpperCase())
    .sorted()
    .toList();

The gain is not brevity so much as that the names say what is happening. A for loop could be doing anything; filter can only be removing items.

JAVA
// The operations you will use most
list.stream().filter(...)             // keep some
             .map(...)                // transform each
             .flatMap(...)            // flatten nested collections
             .distinct()
             .sorted(Comparator.comparing(...))
             .limit(10)
             .toList();

// Terminal operations
.count()
.anyMatch(...)   .allMatch(...)   .noneMatch(...)
.findFirst()     .reduce(...)
.collect(Collectors.groupingBy(Person::getCity))
.collect(Collectors.joining(", "))
.mapToInt(Person::getAge).average()

Streams are lazy: nothing runs until a terminal operation asks for a result. That is what allows a filter followed by findFirst to stop as soon as it has an answer, rather than processing the whole collection.

JAVA
// Grouping and summarising
Map<String, List<Person>> byCity = people.stream()
    .collect(Collectors.groupingBy(Person::getCity));

Map<String, Long> counts = people.stream()
    .collect(Collectors.groupingBy(Person::getCity, Collectors.counting()));

Map<Boolean, List<Person>> split = people.stream()
    .collect(Collectors.partitioningBy(p -> p.getAge() >= 18));

Optional#

JAVA
public Optional<User> findByEmail(String email) {
    // returns Optional.empty() rather than null
}

String name = findByEmail(email)
    .map(User::getName)
    .orElse("Unknown");

findByEmail(email).ifPresent(user -> sendWelcome(user));

User user = findByEmail(email)
    .orElseThrow(() -> new NotFoundException("No user with that email"));

The point is that the return type tells you a value might be absent, so the compiler makes you deal with it. A method returning User gives you no such warning.

The date and time API#

The old Date class was mutable, not thread-safe, counted months from zero and years from 1900. Java 8 replaced it entirely:

JAVA
LocalDate today = LocalDate.now();
LocalDate date = LocalDate.of(2026, 9, 6);          // month 9 means September
LocalDate parsed = LocalDate.parse("2026-09-06");

LocalTime time = LocalTime.of(14, 30);
LocalDateTime moment = LocalDateTime.of(date, time);
ZonedDateTime zoned = ZonedDateTime.now(ZoneId.of("Europe/London"));
Instant instant = Instant.now();                     // a point on the timeline

// Everything returns a new object - these types are immutable
LocalDate deadline = today.plusDays(30).minusWeeks(1);

long days = ChronoUnit.DAYS.between(today, deadline);
Period period = Period.between(birthday, today);
Duration duration = Duration.between(start, end);

String formatted = today.format(DateTimeFormatter.ofPattern("d MMMM yyyy"));

Which type to use is the main decision:

Type Represents Use for
LocalDate a date, no time or zone birthdays, deadlines
LocalDateTime date and time, no zone an appointment in local terms
ZonedDateTime date, time and zone anything crossing time zones
Instant a moment, in UTC timestamps, event logs

Store timestamps as Instant and convert to a zone only when displaying them. Storing local times and hoping is the source of most date bugs.

Default methods#

JAVA
public interface Vehicle {
    void start();

    default void honk() {
        System.out.println("Beep");
    }
}

Before Java 8, adding a method to an interface broke every class implementing it. Default methods made it possible to extend an interface without breaking existing code — which is exactly how stream() was added to every collection in the standard library.

Other additions worth knowing#

JAVA
// Map improvements
map.getOrDefault(key, 0);
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
map.merge(word, 1, Integer::sum);
map.forEach((k, v) -> System.out.println(k + " " + v));

// String joining
String.join(", ", names);

// Repeatable annotations, and type annotations

computeIfAbsent and merge replace the check-then-put pattern that fills up older Java, and they are less error-prone.

What has improved since#

If you are working with Java 8 material, several later additions are worth knowing about:

JAVA
// Java 10: local type inference
var names = new ArrayList<String>();

// Java 11: shorter collectors
List<String> list = stream.toList();     // Java 16, replaces collect(toList())

// Java 14: records
record Point(double x, double y) { }

// Java 15: text blocks
String query = """
    SELECT id FROM products
    """;

// Java 16: pattern matching for instanceof
if (shape instanceof Circle c && c.radius() > 10) { }

// Java 21: virtual threads
Thread.startVirtualThread(() -> handle(request));

Questions people ask#

Are streams slower than loops?

Slightly, because of the lambda dispatch and iterator machinery. On collections of a few thousand items the difference is invisible. In a method called millions of times, measure before choosing.

Should I use parallel streams?

Rarely. They help only for genuinely CPU-bound work on large collections. For small collections or I/O-bound work the coordination overhead makes them slower, and they share a common pool, so one slow parallel stream can affect everything else.

Is Java 8 still used?

Widely, in existing systems. It is long past its most useful life for new work — the releases since have added a great deal, and current long-term support versions receive fixes that Java 8 largely does not.

When should a method return Optional?

When absence is a normal outcome — a lookup that may find nothing. Not for collections, where an empty list already says it, and not for fields or parameters.

Where to go next#

Functional programming, the ideas behind lambdas and streamsRead next

Keep reading

Java

Building a Complete Java Project

Take Java from a single file to a real project: Maven, package structure, dependency injection by hand, tests, configuration, logging and a…

7 min read

Java

Java Design Patterns

The patterns still worth knowing in modern Java — builder, strategy, factory, observer, decorator and singleton — and which the language has…

5 min read

Java

Java: Where to Go From Here

A recap of what Java covers, an honest self-assessment checklist, the three directions to specialise in, and how to keep learning after…

4 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *