GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — Optional.ifPresentOrElse() | java.evolved
Streams
Beginner
Optional.ifPresentOrElse()Handle both present and empty cases of Optional in one call. 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
);
See a problem with this code? Let us know.
Why the modern way wins
📏
Single expressionBoth cases handled in one method call. 🚫
No get()Eliminates the dangerous isPresent() + get() pattern. 🔗
FluentChains 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
Proof
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();
JDK 16+
→
Streams
Advanced
Stream gatherersJava 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();
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()
)
));
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. |