web123456

java8 orElse, orElseGet, orElseThrow usage

These 3 are used to handle null:
orElse uses objects in brackets
orElseGet uses the object returned by the Supplier interface. The supplier interface is just a get method.
There is no entry parameter, and the exit parameter must be the same type as the Optional object.
orElseThrow uses the object returned by the Supplier interface, and this object must implement Throwable. The supplier interface is just a get method. There is no entry parameter, and the exit parameter must be Throwable.

orElse code

//orElse If you have it, use your own value.   If null, use the value after orElse.
//There are genuine products, but there are no genuine products and substitutes.
System.out.println(Optional.ofNullable("Authentic").orElse("Additional"));  // orElse
System.out.println(Optional.ofNullable(null).orElse("Additional"));

orElseGet code

// orElseGet It can pass into a supplier interface, which can implement logic in various ways
System.out.println(Optional.ofNullable("BMW").orElseGet(()->"walk"));  // There is no need to walk with a BMW
System.out.println(Optional.ofNullable(null).orElseGet(()->"bike"));  // You can ride a bicycle without a BMW
System.out.println(Optional.ofNullable(null).orElseGet(()->"Electric Vehicle"));  // You can ride an electric bike without a BMW

Some people may say that orElse and orElseGet do not see the difference.
The difference is that orElseGet can pass in an interface to customize the logic.

orElseThrow code

// There is nothing unusual if you have money
try {
    System.out.println(Optional.ofNullable("money").orElseThrow(()->new Exception()));  // If you have money, you won't throw out abnormalities
} catch (Throwable throwable) {
    throwable.printStackTrace();
}

// If you don't have money, you will throw out abnormally
try {
    System.out.println(Optional.ofNullable(null).orElseThrow(()->new Exception()));  // No money to sell abnormally
} catch (Throwable throwable) {
    throwable.printStackTrace();
}