Java 8 Optional

Java 8 Optional

In this post, we will see about Java 8 optional.

Did you ever get NullPointerException as Java developer? If you are experienced Java developer, you might have got NullPointerException at some point of time.
You might agree that NullPointerException is pain for novice or expert core Java developer. You have to put a lot of defensive code in case you want to avoid NullPointerException.
Let’s see with the help of an example.

Create a main class named "JavaFindEmployeeMain.java"

When you run above program, you will get below output:

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.JavaOptionalMain.main(JavaOptionalMain.java:12)

As you can see, "Adam" is not present in employeeList, that’s why we are getting NullPointerException here.

Do you see the issue here? We forgot to check null when we tried to find employee in the list. This occurs more often when you call library function and it returns null and you forget to check it.


Java 8 Optional

You can use Optional to solve this problem. You can change "JavaOptionalMain" as below.

When you run above program, you will get below output:

There is no employee with name Adam

You might think that you could have handled null in JavaFindEmployeeMain as well but when you return Optional from method, it means that missing value can be expected from method.

Optional Java 8


Ways to create Optional

There are multiple ways to create Optional.

Empty Optional

You can create empty optional object using static factory method "empty"

Optional from a non-null value

You can create Optional from non-null value using static factory method "of"

If employee is null then above method will throw NullPointerException.

Optional from null or non-null value

You can create Optional from null or non null value using static factory method "ofNullable"


Getting value from Optional

You can use get() method to retrieve value from Optional but it is least safe. If value is not present then it will throw NoSuchElementException, so you need to make sure you call isPresent() method before you call get() method.


Check value in Optional

You can check if there is value wrapped inside Optional using isPresent method.


Conditional action in Optional

You can use ifPresent method to execute action if value is present in Optional.
Change main method in JavaOptionalMain as below

When you run this program, you will get below output:

Employee name: Dummy
Employee name: John found in list

As you can see here, if employee name present in the list, then only we are printing employee name else it does not perform any action.


Default value in Optional using orElse

You can return default value in case there is no value in Optional using orElse method.
Change main method in JavaOptionalMain as below

When you run this program, you will get below output:

Employee name: Dummy
Employee name: Martin

Please note that even if value is present in Optional, default object will be crerted.


Default value in Optional using orElseGet

orElseGet is lazy counter part of orElse.It takes supplier as parameter and will be called only if value is not present in Optional.
Change main method in JavaOptionalMain as below

When you run this program, you will get below output:

Employee name: Dummy
Employee name: Martin

Throwing exception from Optional

You can use orElseThrow to throw exception in case Optional is empty. It is similar to get() method but in this case, you can choose to throw any Exception rathar than NoSuchMethodException.
Change main method in JavaOptionalMain as below

Use of Optional in Java 8 APIs

There are lot of uses of Optional in Java 8 APIs.Let me provide you one example.
Stream.findFirst() method returns an Optional with the first element of this stream, or an empty Optional if the stream is empty.

That’s all about Optional in Java 8.

Happy learning!!


import_contacts

You may also like:

Related Posts

  • Format Instant to String in java
    02 May

    How to format Instant to String in java

    Learn about how to format Instant to String in java.

  • Convert Date to LocalDate in java
    12 January

    Java Date to LocalDate

    Table of ContentsUsing toInstant() method of Date classUsing toInstant() method of Date classUsing java.sql.Date In this post, we will see how to convert Date to LocalDate in java. Sometimes, we may need to convert Date to new Java 8 APIs and vice versa. There are multiple ways to convert Date to LocalDate in java. Read […]

  • Convert LocalDate to Date in java
    11 January

    Java LocalDate to Date

    Table of ContentsUsing Instant objectUsing java.sql.Date In this post, we will see how to convert LocalDate to Date. Java 8 has introduced a lot of new APIs for Date and time. There can be many ways to convert Java LocalDateTime to date. Using Instant object You can convert LocalDate to Date using Instant object which […]

  • Convert Stream to List in java
    31 December

    Java Stream to List

    Table of ContentsUsing Collectors.toList()Using Collectors.toCollection()Using foreachFilter Stream and convert to ListConvert infinite Stream to List In this post, we will see how to convert Stream to List in java. There are multiple ways to convert Stream to List in java. Using Collectors.toList() You can pass Collectors.toList() to Stream.collect() method to convert Stream to List in […]

  • Convert LocalDateTime to Timestamp in java
    18 November

    Convert LocalDateTime to Timestamp in Java

    Table of ContentsLocalDateTimeTimestampConvert LocalDateTime to Timestamp In this post, we will how to convert LocalDateTime to Timestamp . Before learning how to convert localdatetime to timestamp, let us learn about LocalDateTime and Timestamp, and understand the importance of this conversion. LocalDateTime LocalDateTime was introcuded in Java 8. LocalDateTime can be imported time package: import java.time.LocalDateTime; […]

  • 28 August

    A In-Depth guide to Java 8 Stream API

    Table of ContentsIntroductionTypes of Stream operationsStream creationEmpty StreamCollection StreamStream.ofStream.generate()Stream.iterate()Lazy evaluationOrder of operationsPrimitive StreamsConvert Stream to IntStreamConvert IntStream to StreamEmployee classCommon intemediate operationsMap()Filter()sorted()limit()Skip()flatmap()Common terminal operationsforeachcollectReducecountallMatch()nonMatch()anyMatch()min()max()Parallel StreamsExercisesExercise 1Exercise 2Exercise 3Exercise 4Excercise 5Excercise 6Excercise 7 In this post, we will see an in-depth overview of Java 8 streams with a lot of examples and exercises. Introduction You may […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.