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!!

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • Unable to obtain LocalDateTime from TemporalAccessor
    20 February

    [Fixed] Unable to obtain LocalDateTime from TemporalAccessor

    Table of ContentsUnable to obtain LocalDateTime from TemporalAccessor : ReasonUnable to obtain LocalDateTime from TemporalAccessor : FixLocalDate’s parse() method with atStartOfDay()Use LocalDate instead of LocalDateTimeWas this post helpful? In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8. Unable to obtain LocalDateTime from TemporalAccessor : Reason You […]

  • Java LocalDate to Instant
    17 February

    Convert LocalDate to Instant in Java

    Table of ContentsJava LocalDate to InstantUsing toInstant() wth ZoneIdUsing toInstant() with ZoneOffsetWas this post helpful? In this article, we will see how to convert LocalDate to Instant in Java. Java LocalDate to Instant Instant class provides an instantaneous point in time. When you want to convert LocalDate to Instant, you need to provide time zone. […]

  • Java Instant to LocalDate
    17 February

    Convert Instant to LocalDate in Java

    Table of ContentsUsing ofInstant method [ Java 9+]Using ZoneDateTime’s toLocalDate() [Java 8]Was this post helpful? In this article, we will see how to convert Instant to LocalDate in java. Using ofInstant method [ Java 9+] Java 9 has introduced static method ofInstant() method in LocalDate class. It takes Instant and ZoneId as input and returns […]

  • Convert String to LocalDateTime in Java
    17 February

    Convert String to LocalDateTime in Java

    Table of ContentsJava String to LocalDateTimeConvert String to LocalDateTime with custom formatWas this post helpful? In this article, we will see how to convert String to LocalDateTime in Java. LocalDateTime class was introduced in Java 8. LocalDateTime represents local date and time without timezone information. It is represented in ISO 8601 format (yyyy-MM-ddTHH:mm:ss) by default. […]

  • Java LocalDateTIme to String
    16 February

    Format LocalDateTime to String in Java

    Table of ContentsJava LocalDateTime To StringConvert LocalDateTime to Time Zone ISO8601 StringParse String to LocalDateTimeWas this post helpful? In this article, we will see how to format LocalDateTime to String in java. Java LocalDateTime To String To format LocalDateTime to String, we can create DateTimeFormatter and pass it to LocalDateTime’s format() method. [crayon-62b6dabb18fc6833343094/] Here are […]

  • Find duplicate elements in the Stream
    17 October

    Java 8 – Find duplicate elements in Stream

    Table of ContentsIntroductionUsing distinct()Using Collections.frequency()Using Collectors.toSet()Using Collectors.toMap()Using Collectors.groupingBy()ConclusionWas this post helpful? Introduction When working with a collection of elements in Java, it is very common to have duplicate elements, and Java provides different APIs that we can use to solve the problem. Java 8 Stream provides the functionality to perform aggregate operations on a collection, […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.