Optional common methods
- isPresent() method returns true when the value of the Optional instance is not empty; otherwise, it returns false;
-
orElseGet() method returns the value when Optional contains a non null value, otherwise a default value is generated through the received function;
-
The map() method converts the value of the current option and returns a new option instance;
-
The orElse() method is similar to the orElseGet method, except that orElse() returns the default value passed in directly.
Real column
- When it's worth it
public static void main(String args[]) { Optional<String> fullName = Optional.ofNullable("Stored value"); System.out.println("Full Name is set? " + fullName.isPresent()); System.out.println("Full Name: " + fullName.orElseGet(() -> "[none]")); System.out.println(fullName.map(s -> "Hey " + s + "!").orElse("Hey Stranger!")); }
- When there is no value
public static void main(String args[]) { Optional<String> fullName = Optional.ofNullable(null); System.out.println("Full Name is set? " + fullName.isPresent()); System.out.println("Full Name: " + fullName.orElseGet(() -> "[none]")); System.out.println(fullName.map(s -> "Hey " + s + "!").orElse("Hey Stranger!")); }
- The get() method is mainly used to return the actual value of the wrapper object, but if the value of the wrapper object is null, NoSuchElementException will be thrown
public T get() { if (value == null) { throw new NoSuchElementException("No value present"); } return value; }
- The isPresent() method is used to determine whether the value of the wrapper object is non empty
public boolean isPresent() { return value != null; }
- ifPresent() method accepts a Consumer object (consumption function). If the value of the wrapper object is not empty, run the accept() method of the Consumer object, and the real column is as the second one
public void ifPresent(Consumer<? super T> consumer) { if (value != null) consumer.accept(value); }
public static void printName(Student student) { Optional.ofNullable(student).ifPresent(u -> System.out.println("The student name is : " + u.getName())); }
- The filter() method accepts the parameter as the Predicate object, which is used to filter the Optional object. If the condition of Predicate is met, the Optional object itself is returned; otherwise, an empty Optional object is returned
public static void filterAge(Student student) { Optional.ofNullable(student).filter( u -> u.getAge() > 18).ifPresent(u -> System.out.println("The student age is more than 18.")); }
- The parameter of the map() method is the Function (functional interface) object. The map() method uses the Function function Function to calculate the wrapped object in the Optional and wrap it into a new Optional object (the type of the wrapped object may change)
public static Optional<Integer> getAge(Student student) { return Optional.ofNullable(student).map(u -> u.getAge()); }
- Unlike the map() method, the return value type of the input parameter Function is Optional instead of U, so flatMap() can map a two-dimensional Optional object into a one-dimensional object
public static Optional<Integer> getAge(Student student) { return Optional.ofNullable(student).flatMap(u -> Optional.ofNullable(u.getAge())); }
- The function of orElse() method is relatively simple, that is, if the value of the wrapper object is not empty, return the value of the wrapper object, otherwise return the value of the parameter other (the default value)
public static String getGender(Student student) { return Optional.ofNullable(student).map(u -> u.getGender()).orElse("Unkown"); }
- The orElseGet() method is similar to the orElse() method, except that the input parameter of the orElseGet() method is a Supplier object, and the return value of the get() method of the Supplier object is used as the default value
public static String getGender(Student student) { return Optional.ofNullable(student).map(u -> u.getGender()).orElseGet(() -> "Unkown"); }
- The orElseThrow() method is actually very similar to the orElseGet() method. The input parameters are Supplier objects, but the Supplier object of orElseThrow() must return a Throwable exception
public static String getGender1(Student student) { return Optional.ofNullable(student).map(u -> u.getGender()).orElseThrow(() -> new RuntimeException("Unkown")); }
The orElseThrow() method is applicable to the scenario where a specific exception needs to be thrown when the value of the wrapper object is null
Optional avoid null pointers shili
- When not optional
public String getUserSteetName(User user) { if(null != user) { Address address = user.getAddress(); if(null != address) { Street street = address.getStreet(); if(null != street) { return street.getStreetName(); } } } return "nothing found";}
- When using Optional
public String getUserSteetName(User user) { Optional<User> userOptional = Optional.ofNullable(user); final String streetName = userOptional.orElse(new User()).getAddress().orElse(new Address()).getStreet().orElse(new Street()).getStreetName(); return StringUtils.isEmpty(streetName) ? "nothing found" : streetName; }
reference
https://www.jianshu.com/p/d81a5f7c9c4e
https://www.cnblogs.com/wuhenzhidu/p/10765655.html