0% found this document useful (0 votes)
3 views28 pages

6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views28 pages

6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Optionals

Concepts
Optional Class

Creating Optionals

Optional Methods

isPresent()

get()

orElse()

orElseGet()

ifPresent()

map()

filter()

More Terminal Operations on Streams

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 Java 8, Optional class is introduced to handle these scenarios in a more effective


way. Using the Optional methods also increases the readability of the code.

In this unit, we'll learn what is Optional class and handling the

null cases in our code using its methods.

1. Optional Class

The

Optional class from the java.util package is designed to be used as a return


type for methods that may or may not return a value. It provides several methods to
help prevent the NullPointerException .

Let's understand

NullPointerException scenarios and handling it with an example,

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

In the above code, we have allocated memory to store

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.

let's try handling

NullPointerException using null checks.

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

In the above code, before calling the

length() method on the element, we have checked whether the element is


String or not.

These cases can be handled in a better way using


Optional s.

1.1 Creating Optionals

The

Optional class provides different methods to create optionals.

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

empty() is a static method that creates an instance of Optional with no values.

Syntax
JAVA

1 Optional.empty();

Here,

Optional is the class name.

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

In the above code, the

Optional.empty() method creates an instance of the Optional with no values


in it.

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,

Optional is the class name.

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]

In the above code, the

Optional.of(324) method creates an instance of the Optional of Integer


type with value as 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,

Optional is the class name.

Example 1: Providing a non-null value as an argument

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]

In the above code, the

Optional.ofNullable(324) method creates an instance of the Optional of


Integer type with value as 324 .

Example 2: Providing a null value as an argument

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

In the above code, the

Optional.ofNullable(null) method creates an empty optional.

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

isPresent() method returns true if any element is present in the optional,


otherwise false is returned.

Syntax
JAVA
1 optional.isPresent();

Here, optional is an instance of the

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

In the above code, we have created an optional with

John as a value. As the optional created consists of a value (John), the


isPresent() method returned 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

Name is: John

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

Supplier (a functional interface) as an argument.

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

orElseGet() method on this optional, it returns the value contained in the


optional, which is John. We then created an empty optional and called the
orElseGet() method on it, which returns the default value specified in the
method, which is Jane.

The

orElseGet() method is generally used when the default value needs to be


computed at runtime.

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

Consumer (a functional interface) type as an argument.

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

Name is: John

In the above code, we have created an optional with John as a value. When we call
the

ifPresent() method on this optional, it performs the operation specified in the


method (i.e. it displays "Name is: John" on the console).

We then created an empty optional and called the


ifPresent() method on it, but no operation is performed because the optional is
empty.

6. map()

The

map() method allows us to perform an operation on each value in an optional and


return the result as a new optional. If the optional is empty, the function is not
applied and an empty optional is returned.

It accepts a

Function (a functional interface) type as an argument.

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

filter() method allows us to filter the values in an optional based on a specific


condition. It accepts a Predicate (a functional interface) type as an argument.

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

Name is too short

3. More Terminal Operations on Streams

In the previous unit, we learned some of commonly used terminal operations such as

forEach , map , etc.

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

findFirst() method returns an Optional containing the first element of the


stream, or an empty Optional if the stream is empty.

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

First name is: John


Stream is empty

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.

We then created an empty stream and called the

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.

In most cases, it returns the first element in the stream.

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

First name is: John


Stream is empty

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.

We then created an empty stream and called the

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

BinaryOperator (a functional interface) type as an argument.

Syntax
JAVA

1 stream.reduce(BinaryOperator);

Here,

BinaryOperator is used to combine a stream of elements into a single result. It


takes two arguments.

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

In the above code, we have used the

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 .

3.1 reduce(identity, BinaryOperator)

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

In the above code, we have used the

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

In the above code, we have used the

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

min() accepts Comparator type as an argument.

Syntax
JAVA

1 stream.min(Comparator);

Let's use the

Comparator.comparingInt() method that does operations in the int type and


returns a Comparator that compares the elements using those int values.

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

In the above code, we have used the

Comparator.comparingInt() method that returns a Comparator that compares


the elements using the integer values produced from comparingInt() method. In
this case, we have taken the Integer s.

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

In the above code, we have used the

Comparator.comparingInt() method that returns a Comparator that compares


the elements using the integer values produced from comparingInt() method. In
this case, we have used the lengths of strings.

5. max()

The

max() method returns the maximum element of a stream. If the stream is empty,
an empty Optional is returned.

The

min() accepts Comparator type as an argument.

Syntax
JAVA

1 stream.max(Comparator);

Let's use the

Comparator.comparingInt() method that does operations in the int type and


returns a Comparator that compares the elements using those int values.

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

In the above code, we have used the

Comparator.comparingInt() method that returns a Comparator that compares


the elements using the integer values produced from comparingInt() method. In
this case, we have taken the Integer s.

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

Comparator.comparingInt() method that returns a Comparator that compares


the elements using the integer values produced from comparingInt() method. In
this case, we have used the lengths of strings.

Summary
Optional
It is designed to be used as a return type for methods that may or may not
return a value.

isPresent() : used to check if an element is present in the optional.

get() : used to get the element in the optional. It throws an exception if


no element is present.

orElse() : used to get a default value (constant value) if the optional is


empty.

orElseGet() : used to get a default value (dynamic value) if the optional


is empty.

ifPresent() : used to perform specified operation on the elements in the


optional.

map() : used to perform a specified operation on elements in an optional


and return a new optional.

filter() : used to filter the elements in an optional based on a specified


condition and return a new optional.

More Terminal Operations on Streams


findFirst() : used to find the first element in a stream.

findAny() : used to find any element in a stream.

reduce() : used to combine a stream of elements into a single result,


using a specified operation.

min() : used to find the minimum element of a stream.


max() : used to find the maximum element of a stream.

You might also like