Search code examples
javarefactoringjava-11

return firts present Optional


I have a few validation cases which returns Optional.empty() or Optional.of(new Object())

How to return the first non empty result of this cases?

on this method I want to return the first not empty case result

public Optional<Object> validate(Objects tmp) {
        Optional<Object> result = case1(tmp);

        if (result.isEmpty()) {
            result = case2(tmp);
        }
        if (result.isEmpty()) {
            result = case3(tmp);
        }
        return result;
    }

case example

private Optional<Object> case1(Object o) {
        if (o == null) {
            return Optional.empty();
        } else {
            return Optional.of(new Object());
        }
    }

Solution

  • Use or to chain these Optionals together. Wrap each subsequent call in a lambda, because or expects a Supplier.

    public Optional<Object> validate(Objects tmp) {
        return case1(tmp)
            .or(() -> case2(tmp))
            .or(() -> case3(tmp));
    }