欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA8之妙用Optional解决判断Null为空的问题

程序员文章站 2022-06-07 12:36:05
...
      CustomerPoJo customerPoJo = null;
      customerPoJo = Optional.ofNullable(customerPoJo).orElse(new CustomerPoJo());
      customerPoJo = Optional.ofNullable(customerPoJo).orElseGet(() -> new CustomerPoJo());
      Optional.ofNullable(customerPoJo).orElseThrow(()->new Exception("客户不存在"));
      CustomerPoJo customerPoJo = new CustomerPoJo();
      customerPoJo.setName("毛亮");
      // 取name的写法
      String name = Optional.ofNullable(customerPoJo).map(u->u.getName()).get();
    User user = new User();
    user.setName("maoliang");
    String name = Optional.ofNullable(user).flatMap(user1 -> user1.getName()).get();
    System.out.println("name=======" + name);
@Data
public class User {

    private String name;

    public Optional<String> getName(){
        return Optional.ofNullable(name);
    }
}

5、filter(Predicate<? super T> predicate)

filter 方法接受一个 Predicate 来对 Optional中包含的值进行过滤,如果包含的值满足条件,那么还是返回这个 Optional;否则返回 Optional.empty

    User user = new User();
    user.setName("maol");
    Optional<User> user1 =
        Optional.ofNullable(user).filter(user2 -> user2.getName().get().length() < 6);
    System.out.println("user1=========="+user1);

结果为:

user1==========Optional[User(name=Optional[maol])]

如果username的长度是小于6的,则返回。如果是大于6的,则返回一个EMPTY对象。

    User user = new User();
    user.setName("maoliang");
    Optional<User> user1 =
        Optional.ofNullable(user).filter(user2 -> user2.getName().get().length() < 6);
    System.out.println("user1=========="+user1);

结果为:

user1==========Optional.empty

以前写法:

    public String getCity(User user){
        if (user != null) {
            if (user.getAddress() != null) {
                Address address = user.getAddress();
                if (address.getCity() != null) {
                    return address.getCity();
                }
            }
        }
        return "";
    }

Java8写法:

    public String getCity(User user) throws Exception {
        return Optional.ofNullable(user)
                .map(user1 -> user1.getAddress())
                .map(a->a.getCity())
                .orElseThrow(()->new Exception("取值错误"));
    }

例二:

    public static void main(String[] args) throws Exception {

        User user = new User();
        if (user != null) {
            doSomething();
        }

        Optional.ofNullable(user).ifPresent(user1 -> {
            doSomething();
        });
    }

    public static void doSomething(){

    }

例三:

    public User getUser(User user) {
        if (user != null) {
            if ("maoLiang".equals(user.getName())) {
                return user;
            }
        }
        User user1 = new User();
        user1.setName("maomao");
        return user1;
    }