Class OptionalEnhancementExamples
java.lang.Object
net.jrodolfo.java_evolution.java09.OptionalEnhancementExamples
Demonstrates
Optional methods added in Java 9.
Java 8 made missing return values explicit with Optional, but some
common workflows still needed awkward code: trying a fallback lookup,
handling present and missing branches together, and flattening many
Optional values into a stream.
Java 9 added Optional.or(java.util.function.Supplier),
Optional.ifPresentOrElse(java.util.function.Consumer, Runnable), and
Optional.stream() to make those workflows direct.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionUsesOptional.ifPresentOrElse(java.util.function.Consumer, Runnable)to handle both branches explicitly.preferredEmail(Optional<String> primary, Optional<String> fallback) UsesOptional.or(java.util.function.Supplier)to try a fallback Optional only when the primary Optional is empty.presentValues(List<Optional<String>> values) UsesOptional.stream()to flatten Optionals into a stream pipeline.
-
Constructor Details
-
OptionalEnhancementExamples
public OptionalEnhancementExamples()
-
-
Method Details
-
preferredEmail
UsesOptional.or(java.util.function.Supplier)to try a fallback Optional only when the primary Optional is empty.- Parameters:
primary- the preferred valuefallback- the fallback value- Returns:
- the primary value when present, otherwise the fallback value
-
describe
UsesOptional.ifPresentOrElse(java.util.function.Consumer, Runnable)to handle both branches explicitly.- Parameters:
value- the Optional to describe- Returns:
- text explaining whether the value was present
-
presentValues
-