--- Optional use of java8

 

 

   //  https://www.jianshu.com/p/82ed16613072 
    1.Optional.of (T value), passing a non- null (or throws NullPointerException) is to construct a value Optional, it contains the value returned by this Optional value. For this method,.
    2.Optional.ofNullable (T value), and the method can be passed a null value (if null , then return is Optional.empty ())
     . 3 .Optional.empty (), the structure Optional empty, i.e. in the Optional It does not contain a value.
   
    isPresent () method is used to determine whether the values ​​contained
    get () to get the value Optional contained (if value does not exist, that calls the get () method on a Optional.empty, it will throw an exception NoSuchElementException)
   
   
     Optional<User> user = Optional.ofNullable(getUserById(id));
     if (user.isPresent()) {
         String username = user.get().getUsername();
         System.out.println("Username is: " + username); // 使用 username
     }
     The code is like looking at a beautiful spot - but in fact it before judgment null difference between the value of the code is not essential, but go with Optional package value,
     Increase the amount of code. So let's look at what Optional also provides a way to make us better (correct posture) use Optional.
     optimization:
      1 .ifPresent
          public  void The IfPresent (Consumer <? Super T> Consumer) {
                 IF (value! = Null ) { // if the value Optional, you consumer.accept the value of calls, or do nothing. 
                    consumer.accept (value)
                }
         }
         So we can be revised as:
         Optional<User> user = Optional.ofNullable(getUserById(id));
         user.ifPresent(u -> System.out.println("Username is: " + u.getUsername()));
     2.orElse
         User user = Optional
            .ofNullable(getUserById(id))
            .orElse(new User(0, "Unknown"));
         System.out.println ( "the Username IS:" + user.getUsername ());
      . 3 distinction .orElseGet orElseGet and orElse method is that, orElseGet method for achieving a parameter passed Supplier interface - Optional when
                     When there is a value, the return value; Optional when no value, the return value obtained from the Supplier.
         User user = Optional
            .ofNullable(getUserById(id))
            .orElseGet(() -> new User(0, "Unknown"));
         System.out.println ( "the Username IS:" + user.getUsername ());
      . 4 .orElseThrow orElseThrow orElse method is distinguished, orElseThrow Optional method when there is a value, the return value;
                     When there is no value will throw an exception, the exception thrown by the incoming exceptionSupplier.
         User user = Optional
            .ofNullable(getUserById(id))
            .orElseThrow (() -> new new EntityNotFoundException ( "the above mentioned id is" + id + "user not found" ));
       For a orElseThrow purposes: in SpringMVC controllers, we can configure unified treatment of various abnormalities. When an entity query, if the database has a corresponding
       Recording method will return the record, otherwise it can throw EntityNotFoundException, processing EntityNotFoundException in return we give the client Http
       Status code 404 and exception information corresponding - orElseThrow perfectly suitable for this scenario.
         @RequestMapping("/{id}")
        public User getUser(@PathVariable Integer id) {
            Optional <the User> User = userService.getUserById (ID);
             return user.orElseThrow (() -> new new an EntityNotFoundException ( "ID of" + id + "user absent" ));
        }
        @ExceptionHandler(EntityNotFoundException.class)
        public ResponseEntity<String> handleException(EntityNotFoundException ex) {
            return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
        }
     5 .map Optional If the current is Optional.empty, still returns Optional.empty; otherwise it returns a new Optional,
             Optional is the comprising: a function mapper in value as the output value to an input.
         Optional<String> username = Optional
            .ofNullable(getUserById(id))
            .map(user -> user.getUsername());
         System.out.println("Username is: " + username.orElse("Unknown"));
         And many times we can use the map operation:
         Optional<String> username = Optional
            .ofNullable(getUserById(id))
            .map(user -> user.getUsername())
            .map(name -> name.toLowerCase())
            .map(name -> name.replace('_', ' '));
         System.out.println ( "the Username IS:" + username.orElse ( "Unknown" ));
      . 6 difference .flatMap flatMap method is that the method map, the map method Mapper function of the output parameter value is, the method would then map use
                 Optional The Optional.ofNullable its packaging; flatMap the required function mapper output parameter is Optional.
         Optional<String> username = Optional
            .ofNullable(getUserById(id))
            .flatMap(user -> Optional.of(user.getUsername()))
            .flatMap(name -> Optional.of(name.toLowerCase()));
         System.out.println ( "the Username IS:" + username.orElse ( "Unknown" ));
      . 7 .filter Predicate accepts a filter to filter the values contained Optional values that satisfy the condition, if included, it is returned
                 The Optional; otherwise Optional.empty.
         Optional<String> username = Optional
            .ofNullable(getUserById(id))
            .filter(user -> user.getId() < 10)
            .map(user -> user.getUsername());
         System.out.println("Username is: " + username.orElse("Unknown"));
   
     Summary: With Optional, we can easily and elegantly handle in your own code null value, and no longer need by reimbursing easy to forget and cumbersome
          IF (Object =! Null to determine the value is not) null . If your program still using JDK before Java8, Google may consider the introduction of Guava library -
         In fact, as early as Java6 era, Guava provides an implementation of the Optional.
   
   

Guess you like

Origin www.cnblogs.com/hahajava/p/12092827.html
Recommended