如何窥视可选?

2022-09-01 02:51:51

我想使用流畅的api并对其应用两个s。OptionalConsumer

我梦见这样的事情:

Optional.ofNullable(key)
    .map(Person::get)
    .ifPresent(this::printName)
    .ifPresent(this::printAddress); // not compiling, because ifPresent is void

如何将几个 s 应用于 ?ConsumerOptional


答案 1

下面介绍如何实现缺少的方法:peekOptional

<T> UnaryOperator<T> peek(Consumer<T> c) {
    return x -> {
        c.accept(x);
        return x;
    };
}

用法:

Optional.ofNullable(key)
    .map(Person::get)
    .map(peek(this::printName))
    .map(peek(this::printAddress));

答案 2

您可以使用以下语法:

ofNullable(key)
    .map(Person::get)
    .map(x -> {printName(x);return x;})
    .map(x -> {printAddress(x);return x;});

推荐