android中优雅的处理nullPointException(java8 Optional)

本文介绍了如何使用Java8的Optional API来避免NullPointerException。通过示例代码展示了Optional的构造函数、map、flatMap、ifPresent、isPresent、orElse等方法的用法,并解释了它们的区别。此外,还讨论了如何在Android低版本中兼容使用Optional。
摘要由CSDN通过智能技术生成

 今天和大家一起使用java8中的Optional API解决nullPointException,
先来看一段代码:


    public class Car {
        private Insurance insurance;
        public Insurance getInsurance() {
            return insurance;
        }
    }


    public class Insurance {
        private String name;
        public String getName() {
            return name;
        }
    }


    public class Person {
        private Car car;
        public Car getCar() {
            return car;
        }
    }

    public String getCarInsuranceName(Person p){
        return p.getCar().getInsurance().getName();
    }

这个getCarInsuranceName()方法一看就知道可能有nullPointException
通常我们这样处理:

public String getCarInsuranceName(Person p){
  if(p!=null){
    Car car = p.getCar();
    if(car!=null){
       Insurane insurance = car.getInsurance();
       if(insurance!=null){
          retu
Java,我们经常需要进行非空判断来避免NullPointException异常的出现。在过去,我们通常会使用if语句来进行判断,但是随着Java 8版本的推出,Optional类和Stream类的引入可以更加简洁和可读地进行代码编写。 Optional类是一个容器对象,它可以容纳一个非空对象或者不包含任何对象(称为“空”)。在使用Optional类时,我们可以利用它提供的isPresent()方法来判断是否包含非空对象,如果是,则可以直接通过get()方法获取该对象。例如: ``` String str = null; Optional<String> optionalStr = Optional.ofNullable(str); if (optionalStr.isPresent()) { System.out.println(optionalStr.get()); } ``` 上述代码可以改写为: ``` String str = null; Optional.ofNullable(str).ifPresent(System.out::println); ``` Stream类是Java 8版本引入的一个新类,它提供了一套函数式编程的API,可以对集合数据进行流式处理。在使用Stream类时,我们可以使用filter方法进行非空判断。例如: ``` List<String> list = Arrays.asList("a", "b", null, "d"); list.stream().filter(item -> item != null).forEach(System.out::println); ``` 上述代码可以改写为: ``` List<String> list = Arrays.asList("a", "b", null, "d"); list.stream().filter(Objects::nonNull).forEach(System.out::println); ``` 使用Optional类和Stream类可以更加简化和优化代码的逻辑,减少代码冗余,提高代码执行效率和可读性。但是,在实际使用时也需要注意,Optional类和Stream类的使用要适当,过度使用反而会导致代码可读性变差和效率降低。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值