If you are using Java 9+, you can use ifPresentOrElse()
method:
opt.ifPresentOrElse(
value -> System.out.println("Found: " + value),
() -> System.out.println("Not found")
);
More Related Contents:
- Uses for Optional
- Should Java 8 getters return optional type?
- Why should Java 8’s Optional not be used in arguments
- How can I count occurrences with groupBy?
- Difference between `Optional.orElse()` and `Optional.orElseGet()`
- Partition a Java 8 Stream
- Why java.util.Optional is not Serializable, how to serialize the object with such fields
- Optional orElse Optional in Java
- Chaining Optionals in Java 8
- What is the difference between Optional.flatMap and Optional.map?
- Why doesn’t java.util.Collection implement the new Stream interface?
- Java lambda returning a lambda
- Does Java SE 8 have Pairs or Tuples?
- Java 8 Supplier with arguments in the constructor
- Why isn’t @FunctionalInterface used on all the interfaces in the JDK that qualify?
- Valid usage of Optional type in Java 8
- Finding enum value with Java 8 Stream API
- Convert String array to Map using Java 8 Lambda expressions
- Purpose of third argument to ‘reduce’ function in Java 8 functional programming
- Is it possible to get next element in the Stream?
- Comparator.reversed() does not compile using lambda
- How do I keep the iteration order of a List when using Collections.toMap() on a stream?
- Is it possible to use the Java 8 Stream API on Android API < 24?
- Simplest way to print an `IntStream` as a `String`
- Grouping by object value, counting and then setting group key by maximum object attribute
- Java 8 UTF-8 encoding issue (java bug?)
- How to use the unsigned Integer in Java 8 and Java 9?
- How to check if exists any duplicate in Java 8 Streams?
- What is the purpose of the default keyword in Java?
- BigDecimal summary statistics