Google Guava Optional - As Short-Circuit Expressions with Multiple Chains

Suppose I have several methods that each one returns optionally. I want to bind them together so that if one of them returns Optional with a value, then the chain should stop propagating and should stop at that point. For example, let's say that f1, f2, f3 each returns Optional.

If I do something like this,

Optional<T> result = f1.or(f2).or(f3);

I see that even if f2 returns the Optional.of (t) parameter, f3 is still called.

I want him to act like a short trailing expression, but that doesn't work.

Can anyone help me with this.

+4
source share
2 answers

Supplier, :

Stream.<Supplier<Optional<T>>>of(this::f1, this::f2, this::f3)
        .map(Supplier::get)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .findFirst();

, , :

public class LazyOptional {
    public static void main(String... args) {
        new LazyOptional().run();
    }

    public void run() {
        Stream.<Supplier<Optional<String>>>of(this::f1, this::f2, this::f3)
                .map(Supplier::get)
                .peek(System.out::println)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .findFirst();
    }

    public Optional<String> f1() {
        return Optional.empty();
    }

    public Optional<String> f2() {
        return Optional.of("a");
    }

    public Optional<String> f3() {
        return Optional.of("b");
    }
}

:

Optional.empty
Optional[a]
+1

Java 8. , Optional<T>, Optional<Optional<T>>.

Optional<Integer> e1 = Optional.empty();
Optional<Integer> e2 = Optional.empty();
Optional<Integer> p = Optional.of(1337);
Optional<Integer> e3 = Optional.empty();
Optional<Integer> e4 = Optional.empty();

// peek used to show output
Optional<Integer> first = Stream.of(e1, e2, p, e3, e4)
    .peek(System.out::println)
    .filter(Optional::isPresent)
    .map(Optional::get)
    .findFirst();

:

Optional.empty
Optional.empty
Optional[1337]
-1

Source: https://habr.com/ru/post/1568427/


All Articles