What's new in java8 - Optional Class

Optional class

So far, the most common cause of java application failure is the notorious null pointer exception. Previously, in order to solve the null pointer exception, Google's famous guava project introduced the Optional class. Guava prevents code pollution by detecting null pointer, and encourages programmers to write cleaner code. Inspired by Google Guava, the Optional class has become part of the java 8 class library.


Optional < T > category( java.util.Optional )It is a container class, which can hold the value of type T, representing the existence of this value. Or just save null to indicate that the value does not exist. Originally, null was used to indicate that a value does not exist. This concept can be better expressed in optional, and null pointer exceptions can be avoided


The javadoc of the Optional class is described as follows: This is a null able container object. If the value exists, the isPresent() method returns true, and a call to the get() method returns the object.


Optional offers many useful ways:

Methods for creating Optional class objects

      Optional.of(T t): to create an optional instance, t must be non empty
      Optional.empty(): create an empty optional instance
      Optional.ofNullable (t t t): t can be null

Determine whether the Optional container contains objects

Boolean isPresent(): interprets whether an object is included

Void ifpresent (Consumer <? Super T > Consumer): if there is a value, execute the implementation code of the Consumer interface, and the changed value will be passed to it as a parameter.

Get the object of the Optional container:

T get(): if the calling object contains a value, return the value, otherwise throw an exception

T orElse(T other): if there is a value, return it; otherwise, return the specified other object.

T orelseget (Supplier <? Extends T > other): if there is a value, it will be returned; otherwise, it will return the object provided by the Supplier interface implementation.

T orelsethrow (Supplier <? Extensions x > exceptionsupplier): if there is a value, return it, otherwise throw an exception provided by the Supplier interface implementation


Code practice


package com.sgl.optional;

import org.junit.Test;
import org.springframework.util.StringUtils;

import java.util.Optional;

 * Optional Class: created to avoid null pointer exceptions in a program.
 * Common method: ofnullable (t t t)
 *              orElse(T t)
 * @author not_simple
 * @version 1.0
 * @date 2020/6/6 15:35
public class OptionalTest {
    Optional.of(T t) :To create an Optional instance, t must be non empty
    Optional.empty() :Create an empty Optional instance
    Optional.ofNullable(T t) : t Nullable
    public void test1(){
        Girl girl = new Girl();
//        girl = null;
        Optional<Girl> optionalGirl = Optional.of(girl);

    public void test2(){
        Girl girl = new Girl();
        girl = null;
//        Optional.ofNullable (t t t): t can be null
        Optional<Girl> optionalGirl = Optional.ofNullable(girl);
        System.out.println(optionalGirl); // Optional.empty
        Girl girl1 = optionalGirl.orElse(new Girl("123"));

    public String getGirlName(Boy boy){
        return boy.getGirl().getName();

    public void test3(){
        Boy boy = new Boy();
        String girlName = getGirlName(boy);
    //The optimized getGirlName() has no Optional
    public String getGirlName1(Boy boy){
        if (!StringUtils.isEmpty(boy)){
            Girl girl = boy.getGirl();
            if (!StringUtils.isEmpty(girl)){
                return girl.getName();
        return null;

    public void test4(){
        Boy boy = new Boy();
        String girlName = getGirlName1(boy);

    //getGirlName() optimized with Optional
    public String getGirlName2(Boy boy){
        Optional<Boy> boyOptional = Optional.ofNullable(boy);
        //At this time, boy1 must not be empty
        Boy boy1 = boyOptional.orElse(new Boy(new Girl("Didi")));
        Girl girl = boy1.getGirl();

        Optional<Girl> girlOptional = Optional.ofNullable(girl);
        //At this time, girl1 must not be empty
        Girl girl1 = girlOptional.orElse(new Girl("Small red"));

        return girl1.getName();

    public void test5(){
//        Boy boy = new Boy(); / / small red
        Boy boy = null; // Didi
        String girlName = getGirlName2(boy);





Tags: Java Google Junit

Posted on Sat, 06 Jun 2020 01:48:40 -0700 by nano