6
6
Concepts
Optional Class
Creating Optionals
Optional Methods
isPresent()
get()
orElse()
orElseGet()
ifPresent()
map()
filter()
findFirst()
findAny()
reduce()
min()
max()
Introduction
In programming, we will be working with different data structures and many times
we require to access a particular data from it. We might get scenarios where the
requested data may not be present in the data structure, in most cases
null will be returned. We have learned to handle these type of scenarios with
if...else or try...catch blocks.
In this unit, we'll learn what is Optional class and handling the
1. Optional Class
The
Let's understand
Code
JAVA
1 class Main {
2 public static void main(String[] arg
3 String[] names = new String[10];
4
5 int lengthOfStr = names[2].lengt
6
7 System.out.println(lengthOfStr);
8 }
9 }
Output
Exception in thread "main" java.lang.Nu
10 strings. Here, the array will be created with null as values. At the statement
names[2].length() , we are trying to call the string method length() on a
null value. So, the NullPointerException is raised.
Code
JAVA
1 class Main {
2 public static void main(String[]
3 String[] names = new String[
4
5 if (names[2] != null) { // n
6 int lengthOfStr = names[
7 System.out.println(lengt
8 } else {
9 System.out.println("Not
10 }
11
Expand
Output
Not a String
The
1. empty()
2. of()
3. ofNullable()
The
Optional does not work with primitive data types like int , double , char ,
etc. So, instead, we need to use its corresponding wrapper classes like Integer ,
Double , Character , etc.
1. empty()
The
Syntax
JAVA
1 Optional.empty();
Here,
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[] arg
5 Optional<Integer> optionalInt =
6
7 System out println(optionalInt);
7 System.out.println(optionalInt);
8 }
9 }
Output
Optional.empty
2. of()
The
of() is a static method that accepts a non-null value as an argument and returns an
instance of the Optional with the specified value.
Syntax
JAVA
1 Optional.of(value);
Here,
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[] arg
5 Optional<Integer> optionalInt =
6
7 System.out.println(optionalInt);
8 }
9 }
Output
Optional[324]
3. ofNullable()
The
ofNullable() is a static method that accepts a value and returns the instance of
Optional with the specified value. If null is provided as a value, it returns an
empty optional.
Syntax
JAVA
1 Optional.ofNullable(value);
Here,
Code
JAVA
1 import java.util.Optional;
2
l i {
3 class Main {
4 public static void main(String[] arg
5 Optional<Integer> optionalInt =
6
7 System.out.println(optionalInt);
8 }
9 }
Output
Optional[324]
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[] arg
5 Optional<Integer> optionalInt =
6
7 System.out.println(optionalInt);
8 }
9 }
Output
Optional.empty
2. Optional Methods
The
Optional class provides several methods to handle the null cases. Some of the
commonly used methods are:
1. isPresent()
2. get()
3. orElse()
4. orElseGet()
5. ifPresent()
6. map()
7. filter()
1. isPresent()
The
Syntax
JAVA
1 optional.isPresent();
Optional class.
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[]
5 Optional<String> optionalName
6
7 boolean check = optionalName
8
9 System.out.println(check);
10 }
11 }
Expand
Output
true
2. get()
The
get() method returns the value contained in the optional. If the optional is empty,
a NoSuchElementException is thrown.
Syntax
JAVA
1 optional.get();
Example 1:
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[]
5 Optional<String> optionalName
6
7 if (optionalName.isPresent()
8 String name = optionalNam
9 System.out.println("Name
10 } else {
11 System.out.println("Optio
Expand
Output
In the above code, we have created an optional with John as a value and checked if
it is present using the
isPresent() method. As the value is present in the optional, we retrieved the value
using the get() method and displayed it on the console. If the optional is empty, a
message is displayed on the console indicating that the optional is empty.
3. orElse()
The
orElse() method returns the value contained in the optional, or a specified default
value is returned if the optional is empty.
Syntax
JAVA
1 optional.orElse();
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[]
5 Optional<String> optionalName
6
7 String name = optionalName.o
8 System.out.println(name);
9
10 optionalName = Optional.empty
11 name = optionalName.orElse("
Expand
Output
John
Jane
In the above code, we have created an optional with John as a value. When we call
the
orElse() method on this optional, it returns the value contained in the optional,
which is John. We then created an empty optional and called the orElse()
method on it, which returns the default value specified in the method, which is
Jane.
The
orElse() method should be used when the default value is a constant or can be
computed at compile time.
4. orElseGet()
The
orElseGet() method returns the value contained in the optional, or the result of
calling a supplier function if the optional is empty.
It accepts a
Syntax
JAVA
1 optional.orElseGet(Supplier);
Example 1:
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[]
5 Optional<String> optionalName
6
7 String name = optionalName.o
8 System.out.println(name);
9
10 optionalName = Optional.empty
11 name = optionalName.orElseGet
Expand
Output
John
Jane
In the above code, we have created an optional with John as a value. When we call
the
The
Example 2:
Code
JAVA
1 import java.util.*;
2
3 class Employee {
4 private String name;
5
6 public Employee(String name) {
7 this.name = name;
8 }
9
10 public String getName() {
11 return name;
Expand
Output
John
Unknown
5. ifPresent()
The
ifPresent() method allows us to specify an operation to be performed if an
element is present in the optional. If the optional is empty, the operation is not
performed.
It accepts a
Syntax
JAVA
1 optional.ifPresent(Consumer);
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[]
5 Optional<String> optionalName
6
7 optionalName.ifPresent(name
8
9 optionalName = Optional.empty
10 optionalName.ifPresent(name
11 }
Expand
Output
In the above code, we have created an optional with John as a value. When we call
the
6. map()
The
It accepts a
Syntax
JAVA
1 optional.map(Function);
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[]
5 Optional<String> optionalName
6
7 Optional<String> optionalUppe
8 System.out.println(optionalU
9
10 optionalName = Optional.empty
11 optionalUpperCaseName = optio
Expand
Output
JOHN
Optional.empty
7. filter()
The
It returns an empty optional if the given optional is empty or if the resultant optional
after the filter operation has no elements.
Syntax
JAVA
1 optional.filter(Predicate);
Example 1:
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[] ar
5 Optional<String> optionalName =
6
7 Optional<String> optionalFilter
8 System.out.println(optionalFilt
9 }
10 }
Output
John
Example 2:
Code
JAVA
1 import java.util.Optional;
2
3 class Main {
4 public static void main(String[] ar
5 Optional<String> optionalName =
6
7 Optional<String> optionalFilter
8 System.out.println(optionalFilt
9 }
10 }
Output
In the previous unit, we learned some of commonly used terminal operations such as
Now, let's learn some more methods used for terminal operations that return
Optionals.
1. findFirst()
2. findAny()
3. reduce()
4. min()
5. max()
1. findFirst()
The
Syntax
JAVA
1 stream.findFirst();
Code
JAVA
1 import java.util.Optional;
2 import java.util.stream.Stream;
3
4 class Main {
5 public static void main(String[]
6 Stream<String> names = Stream
7
8 Optional<String> firstName =
9 firstName.ifPresent(name -> S
10
11 Stream<String> emptyStream =
Expand
Output
In the above code, we have created a stream of names and called the
findFirst() method on it to get the first element of the stream. The method returns
an Optional containing the first element, which we displayed on the console
using the ifPresent() method.
findFirst() method on it, which returns an empty Optional . To handle the case
where the optional is empty, we have used the orElse() method to specify a
default value to be returned if the optional is empty.
2. findAny()
The
findAny() method returns an Optional with any one element of the stream, or
an empty Optional if the stream is empty.
Syntax
JAVA
1 stream.findAny();
Code
JAVA
1 import java.util.Optional;
2 import java.util.stream.Stream;
3
4 class Main {
5 public static void main(String[]
6 Stream<String> names = Stream
7
8 Optional<String> firstName =
9 firstName.ifPresent(name -> S
10
11 Stream<String> emptyStream =
Expand
Output
In the above code, we have created a stream of names and called the
findAny() method on it to get any of the elements in the stream. The method
returns an Optional containing any of the elements, which we displayed on the
console using the ifPresent() method.
findAny() method on it, which returns an empty Optional . To handle the case
where the optional is empty, we have used the orElse() method to specify a
default value to be returned if the optional is empty.
3. reduce()
The
reduce() method combines a stream of elements into a single result and returns an
Optional , using a specified operation.
It accepts a
Syntax
JAVA
1 stream.reduce(BinaryOperator);
Here,
Code
JAVA
1 import java.util.stream.Stream;
2
3 class Main {
4 public static void main(String[] ar
5 Stream<Integer> sum = Stream.of
6
7 sum reduce((a b) -> a + b)
7 sum.reduce((a, b) > a + b)
8 .ifPresent(num -> System.out
9 }
10 }
Output
Sum: 15
reduce() method to reduce an integer stream to a single result using the lambda
expression (a, b) -> a + b , which takes two integers a and b in each
iteration and returns the sum of a and b .
Syntax
JAVA
1 stream.reduce(identity, BinaryOperator);
Here,
identity : The identity element represents both the reduction's initial value
and the default result if there are no elements.
BinaryOperator : It is used to combine a stream of elements into a single
result.
Example 1:
Code
JAVA
1 import java.util.stream.Stream;
2
3 class Main {
4 public static void main(String[] arg
p ( g[] g
5 int sum = Stream.of(1, 2, 3, 4,
6 .reduce(0, (a, b
7 System.out.println("Sum: " + sum
8 }
9 }
Output
Sum: 15
reduce() method to reduce an integer stream to a single result using the lambda
expression (a, b) -> a + b , which takes two integers a and b and returns the
sum of a and b . The initial value is specified as 0 .
Example 2:
Code
JAVA
1 import java.util.stream.Stream;
2
3 class Main {
4 public static void main(String[] arg
5 String concatenation = Stream.of
6 .re
7 System.out.println("Concatenatio
8 }
9 }
Output
Concatenation: abcde
reduce() method to reduce an integer stream to a single result using the lambda
expression (str1, str2) -> str1 + str2 , which takes two integers str1 and str2
and returns the concatenation of str1 and str2 . The initial value is specified as
an empty string "" .
4. min()
The
min() method returns the minimum element of a stream. If the stream is empty,
an empty Optional is returned.
The
Syntax
JAVA
1 stream.min(Comparator);
Example 1:
Code
JAVA
1 import java.util.*;
2 import java.util.stream.Stream;
3
4 class Main {
5 public static void main(String[]
6 Stream<Integer> stream Stre
6 Stream<Integer> stream = Stre
7
8 Optional<Integer> minNum = st
9
10 System.out.println("Minimum:
11 }
Expand
Output
Minimum: 1
Example 2:
Code
JAVA
1 import java.util.*;
2 import java.util.stream.Stream;
3
4 class Main {
5 public static void main(String[]
6 Stream<String> stream = Stre
7
8 Optional<String> minStr = st
9 System.out.println("Minimum:
10 }
11 }
Expand
Output
Minimum: kiwi
5. max()
The
max() method returns the maximum element of a stream. If the stream is empty,
an empty Optional is returned.
The
Syntax
JAVA
1 stream.max(Comparator);
Example 1:
Code
JAVA
1 import java.util.*;
2 import java.util.stream.Stream;
3
4 class Main {
5 public static void main(String[]
6 Stream<Integer> stream = Stre
7
7
8 Optional<Integer> maxNum = st
9
10 System.out.println("Maximum:
11 }
Expand
Output
Maximum: 5
Example 2:
Code
JAVA
1 import java.util.*;
2 import java.util.stream.Stream;
3
4 class Main {
5 public static void main(String[]
6 Stream<String> stream = Stre
7
8 Optional<String> maxStr = st
9 System.out.println("Maximum:
10 }
11 }
Expand
Output
Maximum: pomegranate
In the above code, we have used the
Summary
Optional
It is designed to be used as a return type for methods that may or may not
return a value.