optional

作者: Ary_zz | 来源:发表于2019-10-17 11:12 被阅读0次

    2019-10-17

    orElse

    User user = Optional
            .ofNullable(getUserById(id))
            .orElse(new User(0, "Unknown"));
    

    orElseGet

    User user = Optional
            .ofNullable(getUserById(id))
            .orElseGet(() -> new User(0, "Unknown"));
    

    orElseThrow

    User user = Optional
            .ofNullable(getUserById(id))
            .orElseThrow(() -> new EntityNotFoundException("id 为 " + id + " 的用户没有找到"));
    

    map

    Optional<String> username = Optional
            .ofNullable(getUserById(id))
            .map(user -> user.getUsername())
            .map(name -> name.toLowerCase())
            .map(name -> name.replace('_', ' '));
            
    System.out.println("Username is: " + username.orElse("Unknown"));
    

    flatMap

    use Optional as output

    Optional<String> username = Optional
            .ofNullable(getUserById(id))
            .flatMap(user -> Optional.of(user.getUsername()))
            .flatMap(name -> Optional.of(name.toLowerCase()));
            
    System.out.println("Username is: " + username.orElse("Unknown"));
    

    filter

    Optional<String> username = Optional
            .ofNullable(getUserById(id))
            .filter(user -> user.getId() < 10)
            .map(user -> user.getUsername());
            
    System.out.println("Username is: " + username.orElse("Unknown"));
    

    相关文章

      网友评论

          本文标题:optional

          本文链接:https://www.haomeiwen.com/subject/jmjmmctx.html