Jdk 1.8 optional use of

  Foreword

  In front of a brief introduction to the use of stream flow, this blog focuses on the use of optional classes.

  Google's Guava students know, must know jdk many of which are thought guava reference to inside, optional upgrade is one of them, as early as the java 6, Guava provides a Optional> implementation.

  Closer to home, began to dry

  NullPointerException check is defensive coding process must be dealt with, we could deal with if (null! = User) or Objects.isNull (user), etc., and then after jdk1.8, you can deal with this problem elegantly

  definition

  Optional class is a container object may be a null. If the value exists isPresent () method returns true, call the get () method returns the object.

  Optional is container: it can hold the value of type T, or just to save null. Optional offers many useful ways, so we do not explicitly be null detection.

  Optional introduction of class a good solution to a null pointer exception.

  Examples of presentation methods

  To name a few commonly used functions, and the actual usage analysis

  of

  // create a value of type String Optional Joe Smith

  Optional ofOptional = Optional.of("李四");

  // If we create Optional use of an object method, the passed value is null, then a NullPointerException

  Optional nullOptional = Optional.of(null);

  Usage of a static factory method in fact, examples are as follows:

  @Data

  public class Card {

  private String name;

  private String number;

  private Card() {}

  private Card(String name,String number) {

  this.name = name;

  this.number = number;

  }

  public static Card of() {

  return new Card();

  }

  public static Card of(String name,String number) {

  return new Card(name,number);

  }

  }

  Currently, static factory method more popular, if the target class does not need to subclass the class, highly recommended to use this way.

  get

  If there is value exists Optional object created in this value is returned, if there is no value will throw

  NoSuchElementException abnormal

  ofNullable

  // Create the specified value Optional objects, regardless of the incoming value is null is not null, created when they are not being given

  Optional nullOptional = Optional.ofNullable(null);

  Optional noNullOptional = Optional.ofNullable("李四");

  System.out.println (nullOptional.get ()); // throws an exception NoSuchElementException: No value present

  System.out.println (noNullOptional.get ()); // John Doe

  empty

  // Create an empty String type Optional Object

  Optional emptyOptional = Optional.empty();

  System.out.println (emptyOptional .get ()); // throws an exception NoSuchElementException

  orelse

  It returns the value exists, there is no return to the default value

  Optional stringOptional = Optional.of("张三");

  System.out.println(stringOptional.orElse("zhangsan"));//张三

  Optional emptyOptional = Optional.empty();

  System.out.println (emptyOptional.orElse ( "John Doe")); // John Doe

  orElseThrow

  Optional created if there is value exists, this value is returned, otherwise throw an exception generated by the specified interfaces Supplier

  Optional stringOptional = Optional.of("张三");

  System.out.println(stringOptional.orElseThrow(Exception::new));

  map Zhengzhou gynecological hospital http://www.zykdfkyy.com/

  If the value Optional created existence, provided the value of the execution of the function call Function

  map method performs incoming lambda expression parameter values ​​Optional instance to modify the return value after modification is still a subject Optional

  Optional stringOptional = Optional.of("张三");

  System.out.println (stringOptional.map (e -> e.toUpperCase ()) orElse ( "not empty").);

  stringOptional = Optional.empty();

  System.out.println (stringOptional.map (e -> e.toUpperCase ()) orElse ( "not empty").);

  filter

  If the condition of the filter value Optional created to meet, Optional object containing the value is returned, otherwise it returns an empty Optional objects

  Optional stringOptional = Optional.of("张三");

  System.out.println (stringOptional.filter (e -> e.equals ( "John Doe"))); // Optional [Zhang]

  System.out.println (stringOptional.filter (e -> e.equals ( "John Doe")) orElse ( "John Doe")!); // Zhang

  stringOptional = Optional.empty();

  System.out.println (stringOptional.filter (e -> e.equals ( "John Doe")) orElse ( "John Doe")); // John Doe

  flagMap

  Similar to flatMap map (Funtion) method, except that the mapper returns flatMap

  Value must be Optional, mapping function return value map may be any type of T

  Optional stringOptional = Optional.of("张三");

  System.out.println (stringOptional.flatMap (e -> Optional.of ( "John Doe")) orElse ( "not empty").);

  Probably does not matter how nice feel here after seeing the written judgment or write, let's continue

  actual use

  Person p = new Person ( "John Doe", 11); // if p = null throw "age can not be null" exception

  Integer orElseThrow = Optional.ofNullable(p)

  .map (s -> s.getAge ()) // Returns the parameters for the function with age

  .map (b -> b + 1) // Return parameter to the function 1 + Age

  .filter (m -> m.compareTo (10) == 1) // if older than 10 retained, filtered off less than 10

  .orElseThrow (() -> new Exception ( "Age is not legal")); // if empty Thrown

  System.out.println(orElseThrow);//12

  This usage can be single or multiple (the foreach complex) can be simplified and a large amount of code is determined, unified by throwing exceptions, and the interceptor intercepts exception, unitary, and can greatly improve the development efficiency of the code reader.


Guess you like

Origin blog.51cto.com/14503791/2461643