Java8新特性之Optional

Optional是Java8新特性的新加的类,我们在使用这个类之前先看一下官方的解释:

A container object which may or may not contain a non-null value.
If a value is present, {@code isPresent()} will return {@code true} and
{@code get()} will return the value.

Additional methods that depend on the presence or absence of a contained
value are provided, such as {@link #orElse(java.lang.Object) orElse()}
(return a default value if value not present) and
{@link #ifPresent(java.util.function.Consumer) ifPresent()} (execute a block
of code if the value is present).

This is a <a href="../lang/doc-files/ValueBased.html">value-based</a>
class; use of identity-sensitive operations (including reference equality
({@code ==}), identity hash code, or synchronization) on instances of
{@code Optional} may have unpredictable results and should be avoided.

* @since 1.8

大概意思是说这个类可以是一个为空的类,也可以是个非空类。当这个类是非空的,它方法isPresent()返回的是true。其他的方法取决于这个类是非空还是为空。可以这么说,这个类的使用取决于你对他定义为空对象还是非空对象。
这个的产生意义在于在我们开发过程中可以很好的解决NEP。
我们看这种例子

if (user != null) {
    Address address = user.getAddress();
    if (address != null) {
        Country country = address.getCountry();
        if (country != null) {
            String isocode = country.getIsocode();
            if (isocode != null) {
                isocode = isocode.toUpperCase();
            }
        }
    }
}

嵌套越深,可能我们在开发过程中就会有步骤的遗漏,同时,这样的代码冗长难以维护,且跟业务开发并无直接关联。

主要功能
我们大概可以看到Optional类主要的方法主要有
empty():
该方法是将Null值包装为Optional对象

public static<T> Optional<T> empty() {
    @SuppressWarnings("unchecked")
    Optional<T> t = (Optional<T>) EMPTY;
    return t;
}

of():
创建含值的对象,前提该对象为非Null对象

public static <T> Optional<T> of(T value) {
    return new Optional<>(value);
}

ofNullable():
创建含值的对象,传值参数可以为Null也可以非Null

public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}

get():
获取传参对象,这里如果参数为Null,会抛出异常

public T get() {
    if (value == null) {
        throw new NoSuchElementException("No value present");
    }
    return value;
}

isPresen():
判断参数是否为Null

public boolean isPresent() {
    return value != null;
}

orElse():
如果存在该值,返回值, 否则返回 other

public T orElse(T other) {
    return value != null ? value : other;
}

orElseGet():
如果存在该值,返回值, 否则触发 other,并返回 other 调用的结果

public T orElseGet(Supplier<? extends T> other) {
    return value != null ? value : other.get();
}

主要应用
我们通过代码来了解

import java.util.Optional;
 
public class TestOptional {
   public static void main(String args[]){
   
      TestOptional test = new Java8Tester();
      Integer value1 = null;
      Integer value2 = new Integer(10);
        
      // Optional.ofNullable - 允许传递为 null 参数
      Optional<Integer> a = Optional.ofNullable(value1);
        
      // Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException
      Optional<Integer> b = Optional.of(value2);
      System.out.println(test.sum(a,b));
   }
    
   public Integer sum(Optional<Integer> a, Optional<Integer> b){
    
      // Optional.isPresent - 判断值是否存在
        
      System.out.println("第一个参数值存在: " + a.isPresent());
      System.out.println("第二个参数值存在: " + b.isPresent());
        
      // Optional.orElse - 如果值存在,返回它,否则返回默认值
      Integer value1 = a.orElse(new Integer(0));
        
      //Optional.get - 获取值,值需要存在
      Integer value2 = b.get();
      return value1 + value2;
   }
}

最后我们最开始那段冗长的代码来改造一下

iscode = Optional.ofNullable(user)
        .map(a -> a.getAddress())
        .map(c -> c.getCountry())
        .map(i -> i.getIsocode())
        .map(d -> d.toUpperCase());

这样写是不是更简洁呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值