That's a great question! Optional is much more than just a wrapper for get(). It provides a "functional" way to handle values that might be missing.
Here are some of the most useful methods you should know:
1. orElse() and orElseGet()
These are used to provide a default value if the Optional is empty.
Optional<String> name = Optional.empty();
// orElse: always evaluates the default value even if name is present
String result1 = name.orElse("Default Name");
// orElseGet: takes a Lambda and only runs it if the value is missing (better for performance)
String result2 = name.orElseGet(() -> "Default Name");
2. ifPresent() and ifPresentOrElse()
These allow you to perform actions based on whether the value exists, without manually calling get().
Optional<Integer> maxNum = numbers.stream().max(Integer::compareTo);
// Execute a block of code only if a value is there
maxNum.ifPresent(val -> System.out.println("Found: " + val));
// (Java 9+) Do one thing if present, another if empty
maxNum.ifPresentOrElse(
val -> System.out.println("Found: " + val),
() -> System.out.println("Nothing found!")
);
3. filter()
You can test the value inside the Optional. If it doesn't match the condition, it becomes an empty Optional.
Optional<Integer> result = maxNum.filter(n -> n > 100);
// If maxNum was 30, result is now empty because 30 is not > 100.
4. map() and flatMap()
You can transform the value inside the box without taking it out.
Optional<Integer> maxNum = Optional.of(30);
// Transform the integer to a string
Optional<String> text = maxNum.map(n -> "The number is " + n);
System.out.println(text.get()); // "The number is 30"
5. orElseThrow()
If the value is missing and you consider that an error, you can throw an exception immediately.
Integer value = maxNum.orElseThrow(() -> new RuntimeException("List was empty!"));
Labby's Tip: In modern Java, we try to avoid get() and isPresent() (which look like old-fashioned if-else logic). Instead, we prefer using orElse(), map(), and ifPresent() to keep the code clean and functional!