NullPointerException
and provide a more functional approach to handling null values.
java.util
package.
map()
, filter()
and ifPresent()
for handling optional values.
// Creating an empty Optional
Optional emptyOpt = Optional.empty();
// Creating an Optional with a non-null value
Optional valueOpt = Optional.of("Java 8");
// Creating an Optional that may contain null
Optional nullableOpt = Optional.ofNullable(getValue());
isPresent()
- Returns true if value is present.ifPresent(Consumer action)
- Executes action if value is present.orElse(T other)
- Returns value if present, otherwise returns other
.orElseGet(Supplier other)
- Returns value if present, otherwise invokes Supplier
and returns its result.orElseThrow()
- Returns value if present, otherwise throws NoSuchElementException
.map(Function mapper)
- Applies function if value is present and returns Optional of result.filter(Predicate predicate)
- Returns Optional if value matches predicate, otherwise empty Optional.import java.util.Optional;
public class MainAppOptional
{
public static void main(String[] args)
{
// Creating an Optional with a non-null value
Optional nameOpt = Optional.of("Deepak");
// Checking if value is present
if(nameOpt.isPresent()) {
System.out.println("Value is present: " + nameOpt.get());
}
// Using ifPresent()
nameOpt.ifPresent(name -> System.out.println("Hello, " + name));
// Optional with null value
Optional emptyOpt = Optional.ofNullable(null);
// Using orElse()
String defaultName = emptyOpt.orElse("Default Name");
System.out.println("Value: " + defaultName);
// Using map() and filter()
Optional result = nameOpt
.filter(name -> name.startsWith("D"))
.map(name -> name.toUpperCase());
result.ifPresent(System.out::println);
}
}
Value is present: Deepak Hello, Deepak Value: Default Name DEEPAK
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.