Optional gracefully handles NPE (null pointer) issues
Get Optional objects
- empty()
// Return an empty Optional object Optional<Customer> empty = option.empty ();Copy the code
- Of (T value), creates an Optional that cannot be null
NPE exception Optional<Customer> customerOpt1 = option. of(Customer);Copy the code
- OfNullable (T value) creates an Optional nullable
Optional<Customer> customerOpt2 = option.ofNullable (Customer);Copy the code
Start by creating a Customer class with the following attributes
public class Customer {
private String id;
private String name;
//get setAnd constructor @override public StringtoString() {
return "Customer{" +
"id='" + id + '\'' + ", name='" + name + '\'' + '}'; }}Copy the code
And ifPresent isPresent () ()
IsPresent (): checks whether the value exists
- Java7
if(customer ! = null) { //doSomething
}
Copy the code
- Java8
if (customerOpt1.isPresent()) {
// doSomething
}
Copy the code
IfPresent (): process logic if the value exists, otherwise skip
- Java7
if(customer ! = null) {if(customer.getId().length() == 1) { System.out.println(customer.getName()); }}Copy the code
- Java8
customerOpt1.ifPresent(c -> {
if(c.getId().length() == 1) { System.out.println(c.getName()); }});Copy the code
OrEls & orElseGet & orElseThrow difference
If it’s all Optional and it’s empty, do the opposite
- OrElse: returns value directly if a value exists, otherwise returns other as input
Public T orElse(T other) {returnvalue ! = null ? value : other; }Copy the code
Customer cus = new Customer(); cus.setId("123");
Customer customerElse = Optional.ofNullable(cus).orElse(new Customer("456"."Tom")); System.out.println(customerElse); / / output Customer {id ='123', name='null'}
Copy the code
- OrElseGet: Returns value directly if value exists, otherwise executes input other
Public T orElseGet(Supplier<? extends T> other) {returnvalue ! = null ? value : other.get(); }Copy the code
// example Customer cus = null; Customer customerGet = Optional.ofNullable(cus).orElseGet(() -> new Customer("456"."Keven")); System.out.println(customerGet); / / the Customer {id ='456', name='Keven'}
Copy the code
- OrElseThrow: Returns value if the value exists, otherwise throws an exception
Public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {if(value ! = null) {return value;
} else{ throw exceptionSupplier.get(); }}Copy the code
// example Customer cus = null; Customer customerElse = Optional.ofNullable(cus).orElseThrow(RuntimeException::new); System.out.println(customerElse);Copy the code
filter
You can filter the values you want
Optional<Customer> cusOpt = customer1 .filter(c -> c.getId() ! = null && c.getName().length() > 2);Copy the code
map
You can get the values you want
String s = customer1
.map(c -> c.getName()).orElse("null value");
Copy the code