GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Optional.ifPresentOrElse() | java.evolved

Home / Streams / Optional.ifPresentOrElse()
Streams Beginner

Optional.ifPresentOrElse()

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Handle both present and empty cases of Optional in one call.

Optional
Code Comparison
✕ Java 8
Optional<User> user = findUser(id);
if (user.isPresent()) {
    greet(user.get());
} else {
    handleMissing();
}
✓ Java 9+
findUser(id).ifPresentOrElse(
    this::greet,
    this::handleMissing
);
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
📏

Single expression

Both cases handled in one method call.

🚫

No get()

Eliminates the dangerous isPresent() + get() pattern.

🔗

Fluent

Chains naturally after findUser() or any Optional-returning method.

Old Approach
if/else on Optional
Modern Approach
ifPresentOrElse()
Since JDK
9
Difficulty
Beginner
JDK Support
Optional.ifPresentOrElse()
Available

Widely available since JDK 9 (Sept 2017)

How it works

ifPresentOrElse() takes a Consumer for the present case and a Runnable for the empty case. It avoids the isPresent/get anti-pattern.

Related Documentation
Optional.ifPresentOrElse() ↗
Proof
View proof source ↗
Related patterns
Streams Beginner

Stream.toList()

Java 8
List<String> result = stream
    .filter(s -> s.length() > 3)
    .collect(Collectors.toList());
Java 16+
List<String> result = stream
    .filter(s -> s.length() > 3)
    .toList();
Hover to see modern ➜
JDK 16+ →
Streams Advanced

Stream gatherers

Java 8
// Sliding window: manual implementation
List<List<T>> windows = new ArrayList<>();
for (int i = 0; i <= list.size()-3; i++) {
    windows.add(
        list.subList(i, i + 3));
}
Java 24+
var windows = stream
    .gather(
        Gatherers.windowSliding(3)
    )
    .toList();
Hover to see modern ➜
JDK 24+ →
Streams Intermediate

Collectors.flatMapping()

Java 8
// Flatten within a grouping collector
// Required complex custom collector
Map<String, Set<String>> tagsByDept =
    // no clean way in Java 8
Java 9+
var tagsByDept = employees.stream()
    .collect(groupingBy(
        Emp::dept,
        flatMapping(
            e -> e.tags().stream(),
            toSet()
        )
    ));
Hover to see modern ➜
JDK 9+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.