Sunday, April 12, 2020

Java 8 Optional orElseGet() Example

1. Introduction

In this tutorial, We'll learn java 8 Optional API orElseGet() method examples and where to use.

2. Syntax

[lock]
public T orElseGet(Supplier<? extends T> other)

Return the value if present, otherwise invoke other and return the result of that invocation. This method takes the Supplier Functional Interface. [/lock]

if the Supplier is null, it throws NullPointerException.




3. Optional orElseGet() Example


If optional is non empty then it returns the value from Optional.
If optional is empty then it executes the given supplier and returns supplier result.

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

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

public class OptionalOrElseGetExample {

 public static void main(String[] args) {

  // optional non empty
  Optional<List<String>> listOptional = Optional.of(Arrays.asList("one", "two", "three"));

  List<String> orELseList = listOptional.orElseGet(() -> {
   List<String> list = new ArrayList<String>();
   list.add("Four");
   return list;
  });

  System.out.println("Optional is not empty : " + orELseList);

  // optional empty
  Optional<List<String>> emptyOptional = Optional.empty();

  List<String> orELseGetList = emptyOptional.orElseGet(() -> {
   List<String> list = new ArrayList<String>();
   list.add("Four");
   return list;
  });
  System.out.println("For empty optional resulst : " + orELseGetList);
 }

}

Output:

Optional is not empty : [one, two, three]
For empty optional resulst : [Four]

4. Optional Integer value checking with orElseGet()


Optional take int value and get the value. If optional has value then it returns the value from Optional. If the optional is empty then it executes the Supplier and returns value -999. This value indicates as a default value if optional has no value.

public static void orElseGet() {

  // optional non empty
  Optional<Integer> listOptional = Optional.of(12345);

  Integer value = listOptional.orElseGet(() -> -999);

  System.out.println("Optional not empty integer value : " + value);

  // optional empty
  Optional<Integer> emptyOptional = Optional.empty();

  Integer orELseGetList = emptyOptional.orElseGet(() -> -999);
  System.out.println("For empty optional result : " + orELseGetList);

 }

Output:

Optional not empty integer value : 12345
For empty optional result : -999
 

5. Conclusion

In this article, we've seen how to use java 8 Optional orElseGet() method.

GitHub Code

API

No comments:

Post a Comment