关于java:Java之Optional扫盲

5次阅读

共计 2545 个字符,预计需要花费 7 分钟才能阅读完成。

创立一个 Optional

1、创立一个能够蕴含 null 的 Optional

    Optional<String> optional = Optional.ofNullable(null);

2、创立一个蕴含 null 的 Optional

    Optional<Object> empty = Optional.empty();

这两个代码的意思是统一的

3、创立一个不能蕴含 null 的 Optional

    Optional<String> optional = Optional.of("abc");      public static <T> Optional<T> of(T value) {return new Optional<>(value);    }     private Optional(T value) {this.value = Objects.requireNonNull(value);    }     public static <T> T requireNonNull(T obj) {if (obj == null)            throw new NullPointerException();        return obj;}

从代码调用过程来看,of 办法不能接管 null 值,否则会间接抛出空指针异样。


判断是否 null

1、应用 isPresent() 来判断是否为 null

        Optional<String> optional = Optional.of("abc");        System.out.println(optional.isPresent());//true         Optional<String> empty = Optional.empty();        System.out.println(empty.isPresent());//false         Optional<String> nullOption = Optional.ofNullable(null);        System.out.println(nullOption.isPresent());//false

Option 类中的其余办法

这边会波及到一些 Consumer、Supplier、用法,能够先参考我的另外一篇文章疾速了解 Consumer、Supplier、Predicate 与 Function

get(),获取值

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

看进去,get() 只能用于不为 null 的状况下,否则间接抛出 NoSuchElementException 异样

ifPresent(),如果不为 null,则去进行生产

    public void ifPresent(Consumer<? super T> consumer) {if (value != null)            consumer.accept(value);    }

orElseGet(),如果为 null,则应用 Supplier 中供应的值

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

orElse(),如果为 null,则间接应用传入的值

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

orElseThrow(),如果为 null,则抛出某种异样

    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {if (value != null) {return value;} else {throw exceptionSupplier.get();        }    }

除了以上的办法,还有 map、flatmap、filter 等,这些办法和 Stream 中的同名办法相似,只不过 Optional 中的这些办法返回一个 Option,而 Stream 中返回一个 Stream。


应用 Option 来革新你的代码

外汇赠金流动 https://www.kaifx.cn/activity/

示例 1:输入用户的 id

        // 革新前        if (user!=null){System.out.println(user.getId());        }         // 革新后        Optional.ofNullable(user)                .map(User::getId)                .ifPresent(System.out::println);

示例 2:当用户没有年龄时,应用默认值 20 岁

        // 革新前        int age1 = 0;        if (user != null) {if (user.getAge() == null) {age1 = 20;} else {age1 = user.getAge();            }        }         // 革新后        int age2 = Optional.ofNullable(user)                .map(User::getId)                .orElse(20);

示例 3:当用户的姓名为空时,抛出异样

        // 革新前        if (user != null) {String name = user.getName();            if (name == null) {throw new Exception();            }        }         // 革新后        Optional.ofNullable(user)                .map(User::getName)                .orElseThrow(Exception::new);

示例 4:当用户的年龄大于 18 岁时,输入一个其大写模式的姓名,当姓名不存在时,输入 Unknown

        // 革新前        if (user != null) {int age = user.getAge();            if (age > 18) {String name = user.getName();                if (name != null) {System.out.println(name);                } else {System.out.println("Unknown");                }            }        }          // 革新后        Optional.ofNullable(user)                .filter(u -> u.getAge() > 18)                .map(User::getName)                .map(String::toUpperCase)                .or(() -> Optional.of("Unknown"))                .ifPresent(System.out::println);
正文完
 0