Class OptionalExamples
java.lang.Object
net.jrodolfo.java_evolution.java08.OptionalExamples
Demonstrates
Optional, introduced in Java 8 as a container for values
that may be absent.
Before Java 8, many methods returned null when a value could not be
found. That made absence invisible in the method signature, so callers had
to remember defensive checks and failures often appeared later as
NullPointerExceptions.
Optional solves part of that problem by making absence explicit in a
return type. A method returning Optional<String> communicates that a
value may be missing and encourages the caller to handle that case with
operations such as map, filter, orElseGet, and
orElseThrow. It is most useful as a return type, not as a replacement
for every nullable field or parameter.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classSmall Java 8-style data class used by the Optional examples. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionUsesOptional.orElse(Object)to provide a default value.UsesOptional.orElseGet(java.util.function.Supplier)to create a fallback only when the Optional is empty.UsesOptional.flatMap(java.util.function.Function)when the transformation already returns an Optional.Wraps a possibly null user email in anOptional.Transforms and validates a value while it is inside an Optional.UsesOptional.orElseThrow(java.util.function.Supplier)when the missing value should be treated as an error.
-
Constructor Details
-
OptionalExamples
public OptionalExamples()
-
-
Method Details
-
findEmail
Wraps a possibly null user email in anOptional.- Parameters:
user- the user to inspect, which may benull- Returns:
- an Optional containing the email when both user and email exist
-
displayEmail
UsesOptional.orElse(Object)to provide a default value.- Parameters:
user- the user to inspect- Returns:
- the user's email, or a default message when the email is missing
-
displayEmailGeneratedLazily
UsesOptional.orElseGet(java.util.function.Supplier)to create a fallback only when the Optional is empty.- Parameters:
user- the user to inspect- Returns:
- the user's email, or a lazily generated fallback message
-
requireEmail
UsesOptional.orElseThrow(java.util.function.Supplier)when the missing value should be treated as an error.- Parameters:
user- the user to inspect- Returns:
- the required email
-
normalizeEmail
Transforms and validates a value while it is inside an Optional.- Parameters:
user- the user to inspect- Returns:
- a normalized email when a valid email is present
-
findCompanyDomain
UsesOptional.flatMap(java.util.function.Function)when the transformation already returns an Optional.- Parameters:
user- the user to inspect- Returns:
- the company email domain, excluding personal Gmail addresses
-