In Java 8, Optional<T>
is a container object used to represent the presence or absence of a value. It's commonly used to avoid null
checks and NullPointerException
.
Below are different ways to create an Optional
object in Java 8:
1. Using Optional.of(T value)
Creates an Optional
with a non-null value.
String name = "John";
Optional<String> optional = Optional.of(name);
🔴 Throws NullPointerException
if name
is null.
2. Using Optional.ofNullable(T value)
Creates an Optional
that may hold a null value.
String name = getName(); // could return null
Optional<String> optional = Optional.ofNullable(name);
✅ Safe way to wrap possibly null values.
3. Using Optional.empty()
Creates an explicitly empty Optional
.
Optional<String> optional = Optional.empty();
✅ Used to represent absence of a value clearly.
4. Using Optional
with Streams
Create optional from stream using terminal operation like findFirst()
or findAny()
:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Optional<String> firstName = names.stream().findFirst();
5. Using Optional
with filter
, map
, etc.
Creating or modifying optionals using functional operations:
Optional<String> optional = Optional.of("test")
.filter(s -> s.length() > 2)
.map(String::toUpperCase);
6. Wrapping a method return
If a method might return null, you can wrap the return value:
public Optional<String> getUserName(User user) {
return Optional.ofNullable(user.getName());
}
Comments
Post a Comment