Junior (0-2 years)Java

What are the main features of Java 8: lambdas, streams and Optional?

Quick answer

Java 8 introduced lambda expressions, functional interfaces, the Stream API for declarative collection processing, Optional to represent missing values, default methods in interfaces, method references and the java.time date and time API.

A lambda is a short way to write an instance of a functional interface (an interface with one abstract method), such as Comparator or Runnable. The Stream API lets you describe a pipeline: a source, zero or more intermediate operations such as filter and map that are lazy, and a terminal operation such as collect that triggers the work.

Use Optional as a return type to make absence explicit instead of returning null, but not for fields or method parameters. Streams do not modify the source collection, and parallel streams should be used with care: they only help for large, CPU-bound, stateless operations.

List<String> names = users.stream()
    .filter(u -> u.isActive())
    .map(User::getName)
    .sorted()
    .collect(Collectors.toList());

Optional<User> user = repository.findById(id);
String email = user.map(User::getEmail).orElse("unknown");

Key points

  • Lambdas implement functional interfaces
  • Stream intermediate operations are lazy until a terminal operation runs
  • Optional is for return values, not fields or parameters