☕ Java
Optional Class in Java 8
NullPointerException has been called 'the billion dollar mistake'. Optional is Java's solution: a wrapper that forces you to think about whether a value might be absent, instead of blindly assuming it exists.
Why Optional? The Problem with null
Imagine you call userRepository.findById(123). The user might exist, or might not. Before Optional:
User user = userRepository.findById(123);
System.out.println(user.getEmail()); // BOOM if user is null — NullPointerException
You'd have to remember to check for null everywhere, and when you forget, the app crashes.
Optional<User> wraps the result and forces the caller to handle both cases explicitly: "there might be a value, or there might not be — deal with it."
Java
import java.util.Optional;
// Creating Optionals
Optional<String> present = Optional.of("alice@email.com"); // must be non-null
Optional<String> empty = Optional.empty(); // explicitly empty
Optional<String> maybe = Optional.ofNullable(getUserEmail()); // might be null
// Check and access — verbose but safe
if (present.isPresent()) {
System.out.println(present.get()); // alice@email.com
}
// orElse — provide a fallback value if empty
String email = empty.orElse("no-email@placeholder.com");
// orElseGet — lazily compute the fallback (better for expensive defaults)
String email2 = empty.orElseGet(() -> generateDefaultEmail());
// orElseThrow — throw a custom exception if empty
String email3 = maybe.orElseThrow(() ->
new RuntimeException("Email not found for user")
);
// ifPresent — run code only if value exists (no explicit null check)
present.ifPresent(e -> System.out.println("Sending email to: " + e));
// map — transform the value if present, return empty if not
Optional<Integer> emailLength = present.map(String::length); // Optional[17]Related Topics in Java 8 Features
Lambda Expressions
Java 8's lambdas let you pass behavior as data — write functions inline, without the ceremony of anonymous classes. They make your code dramatically shorter and more expressive, especially when working with collections.
Stream API
The Stream API completely changed how Java developers work with collections. Instead of writing for loops and if statements to filter, transform, and aggregate data, you chain descriptive operations. It reads like a SQL query, runs efficiently, and handles parallelism for free.