Backend Development 8 min read

Master Java 8 Optional and Lambda: Reduce Null Checks and Write Cleaner Code

This tutorial explains how Java 8's Optional class and lambda expressions simplify null handling and collection processing, offering concise code examples, method summaries, and a clear comparison with Java 7 approaches to improve readability and development efficiency.

macrozheng
macrozheng
macrozheng
Master Java 8 Optional and Lambda: Reduce Null Checks and Write Cleaner Code

Many developers still use JDK8; this article introduces useful JDK8 features such as Optional and lambda expressions.

Optional class

Optional helps handle nulls elegantly, avoiding NullPointerException.

Java7 null‑check example:

<code>User user = usersMapper.selectUserById(userId);
String userName = user.getUserName();
if (user != null) {
    if (userName != null && !userName.isEmpty()) {
        // ...
    }
}
</code>

Java8 Optional version:

<code>User user = usersMapper.selectUserById(userId);
Optional.ofNullable(user)
        .map(User::getUserName)
        .ifPresent(userName -> {
            // ...
        });
</code>

Common Optional methods:

ofNullable – returns Optional of value or empty if null

empty – returns empty Optional

filter – returns Optional if value matches predicate

flatMap – applies function returning Optional

get – returns value or throws NoSuchElementException

ifPresent – executes consumer if value present

isPresent – true if value present

map – applies function and wraps result in Optional

of – wraps non‑null value, throws NPE if null

orElse – returns value or default

orElseGet – returns value or result of Supplier

orElseThrow – returns value or throws supplied exception

Difference between

map

and

flatMap

:

map

takes

Function<? super T, ? extends U>

and wraps the result in an Optional;

flatMap

takes

Function<? super T, Optional<U>>

and returns the Optional directly.

<code>map:
public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else
        return Optional.ofNullable(mapper.apply(value));
}

flatMap:
public <U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else
        return Objects.requireNonNull(mapper.apply(value));
}
</code>

Lambda expressions

Lambda provides a concise way to pass behavior as parameters, replacing anonymous inner classes.

Java7 loop vs Java8 lambda:

<code>Java7:
List<String> stringList = Arrays.asList("1","2","3");
for (String st : stringList) {
    System.out.println(st);
}

Java8:
Arrays.asList("1","2","3").forEach(st -> {
    System.out.println(st);
});
</code>

Adopting these features reduces boilerplate, improves readability, and boosts development efficiency.

JavalambdaFunctional ProgrammingJDK8code examplesOptional
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.