Optional java in class learning

Optional actually a container which is mounted a container of an object. This object may be empty, may be non-empty.

Optional class may be used to avoid NullPointerException, to avoid frequent determination section processes a null object

1, the object created Optional method:
  (1) Optional.of (XX); means a non-null only objects
  (2) Optional.ofNullable (x); means may be a null object
  (3) Optional <T> empty () directly returns an empty box objects
 2, how to remove the object Optional container
  (1) get () must fit of (xx) used, because the inside of objects can not be null
  (2) orElse (T OTHER) If Optional container the object is empty, with the other place
  if Optional objects in the container is empty, with the other this supply type interface provides an object instead of (. 3) orElseGet (Supplier <? the extends T> other)
  (. 4) orElseThrow (Supplier <? the extends X-> exceptionSupplier)
. 3, other operations
  Optional <T> filter (Predicate < ? super T> predicate)

Example:

Optional <String> opt = Optional.ofNullable ( "Optional") ;, parameter can be passed a null

opt.orElse ( "other"); // if null, use other alternative

Guess you like

Origin www.cnblogs.com/dirsoen/p/12658449.html