Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading