Wednesday, September 11, 2019

Java 8 Optional ifPresent() - Working Example

1. Overview


In this tutorial, We'll learn how to perform an action if a value is present in Optional. Java 8 Optional ifPresent() does the job for us.

Instead of directly getting the value using get() method, first, it checks the condition value != null.

java-8-optional-ifpresent


The old way is done using the isPresent() method as below. But, ifPresent is much simplified than isPresent().


Optional opt = Optional.of("string");
if(opt.isPresent()) {
    Integer value = opt.get();
    // do something with value
}

2. Syntax


ifPresent() method takes Consumer as an argument and this method expects the Consumer implementation as Lambda Expression.

public void ifPresent(Consumer<? super T> action)

If the value is not present then it does nothing.
If we pass the action as null then throws NullPointerException

3. Examples


In this program, Creating an Optional instance which is a type of List as listOptional. Now, Calling listOptional.ifPresent() method that takes the Consumer. 

list -> list.forEach(value -> System.out.println(value))

The above line is for Consumer logic. This takes the list as value and the printing list values sequential order.


package com.java.w3schools.blog.java8.optional;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class OptionalIfPresentExample {
         
      public static void main(String[] args) {
           
           // Example 1
           Optional<List<String>> listOptional = Optional.of(Arrays.asList("Rupad", "Mastana", "Jago"));
           listOptional.ifPresent(list -> list.forEach(value -> System.out.println(value)));
           
           System.out.println("----------");
           // Example 2
           Optional<String> statement = Optional.of("this is example program on ifPresent method.");
           statement.ifPresent( value -> System.out.println(value.toUpperCase()));
      
      }
 }

Output:


Rupad
Mastana
Jago
----------
THIS IS EXAMPLE PROGRAM ON IFPRESENT METHOD.

If Optional is not having value then it does not perform the given action.

Optional<String> nullOptional = Optional.ofNullable(null);
nullOptional.ifPresent(value -> System.out.println("The null value is " + value));

No output for this code. Because value is null. Let us see how ifPresent() method works internally then we will understand the null case why action is not getting executed.

4. Internal Implementation


The below code is from Optional API.

public void ifPresent(Consumer<? super T> action) {
    if (value != null) {
        action.accept(value);
    }
}

Internally, It checks the condition value != null. That means if the value is null, the execution pointer does not go to the action invocation.
In null case, value != null condition returns false. So, Condition is failing and skipping the action execution part.

5. Conclusion


In this article, We've covered how to perform a consumer action if a value present in the Optional instance. This is done using Optional.ifPresent() method.

Note: Action will be executed if Optional has if and only if it has a non-null value.

Even though if you want to perform some action if the value is null then we must use ifPresentOrElse(action, emptyAction) method of Optional class.


Also, we've seen how it works internally.

Example codes shown in this article are available over GitHub.
API Ref
StackOverFlow

No comments:

Post a Comment