In Java 8 and later versions, the Optional
class is part of the java.util
package and provides a way to handle null values in an effective way and helps to avoid NullPointerExceptions. The Optional class lets you put a value that might be empty or null inside it. This helps you do things safely without needing to directly check if the value is null. Let’s learn today how you can use the Optional
class to handle null values: How to use the Optional class in Java 8 to handle null values
How to use the Optional class in Java 8 to handle null values? Share on X
- Create an
Optional
instance:- To create an
Optional
instance with a non-null value, you can useOptional.of(value)
. - To create an
Optional
instance with a nullable value, you can useOptional.ofNullable(value)
.
- To create an empty
Optional
, you can useOptional.empty()
.
- To create an
- Access the value inside an
Optional
:- You can use the
get()
method to retrieve the value from anOptional
. But, be careful when using this method, because it may throw aNoSuchElementException
if theOptional
is empty.
- You can use the
- Check if the
Optional
has a value:- You can use the
isPresent()
method to check if theOptional
contains a value. - On the other hand, you can also use the
ifPresent(Consumer<T> consumer)
method to perform an action on the value if it is present.
- You can use the
- Handle the missing value:
- You can use the
orElse(T other)
method to provide a default value if theOptional
is empty. - You can use the
orElseGet(Supplier<? extends T> supplier)
method to supply a default value using aSupplier
if theOptional
is empty.
- You can use the
Here’s an example on the usage of Optional
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | /** * Use of Optional method in Java 8 * @author Deepak Verma * */ import java.util.Optional; public class OptionalExample_Java8 { public static void main(String[] args) { // Case 1: Create Optional instances Optional<String> nonNullValue = Optional.of("Hello, my Fellow Programmers!"); Optional<String> nullableValue = Optional.ofNullable(null); Optional<String> emptyOptional = Optional.empty(); // Case 2: Get the value present inside Optional if (nonNullValue.isPresent()) { System.out.println("Non-null Value: " + nonNullValue.get()); } nullableValue.ifPresent(value -> System.out.println("Nullable Value: " + value)); // Case 3: Handling the missing value String originalText = nonNullValue.orElse("Original Value"); System.out.println("Original Value: " + originalText); String providedValue = emptyOptional.orElseGet(() -> "Provided Value"); System.out.println("Provided Value: " + providedValue); try { emptyOptional.orElseThrow(() -> new RuntimeException("Value is not there. Hence, missing.")); } catch (RuntimeException e) { System.out.println("Exception: " + e.getMessage()); } } } |
Output:
1 2 3 4 | Non-null Value: Hello, my Fellow Programmers! Original Value: Hello, my Fellow Programmers! Provided Value: Provided Value Exception: Value is not there. Hence, missing. |
find first non repeated character in a string using Java 8
By using the Optional
class, one can surely make the code more robust and less prone to NullPointerExceptions, as it encourages us to handle the presence or absence of values explicitly.
Use of Optional() class in Java 8..!!! Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: