Java OptionalInt example

OptionalInt allows us to create an object which may or may not contain a int value. If a value is present, isPresent() will return true and getAsInt() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse().
Other classes similar to OptionalInt are OptionalFloat, OptionalDouble, Optional. These can help us eliminate exceptions that occur due to the absence of a value at runtime. Basically we need to first check if the Optional is carrying any value then only try to get value.
In this example we are returning an OptionalInt from Stream created from integer array and finally returning the sum using reduce method. If the Value is present then only we are trying to pring the value by calling result.getAsint()
package javaexp.blogspot.stream;

import java.util.Arrays;
import java.util.OptionalInt;

public class OptionalIntExample {

  public static void main(String[] args) {
    int iarray[] = {9, 10, 11, 12, 15, 15, 25};
    
    OptionalInt result = Arrays.stream(iarray).reduce((left, right) ->left );
    
    if (result.isPresent() ) {
      System.out.println("Sum of Array " + result.getAsInt());
    }
    
  }

}

Summary

OptionalInt and other respective Optional classes helping in protecting from Nullpointer exception when we try to get value (say integer value) from and Integer object which is null.