Chaining Optionals in Java 8

前端 未结 5 958
刺人心
刺人心 2020-11-29 01:48

Looking for a way to chain optionals so that the first one that is present is returned. If none are present Optional.empty() should be returned.

Assumi

5条回答
  •  春和景丽
    2020-11-29 02:23

    You could do it like this:

    Optional resultOpt = Optional.of(find1()
                                    .orElseGet(() -> find2()
                                    .orElseGet(() -> find3()
                                    .orElseThrow(() -> new WhatEverException()))));
    

    Though I'm not sure it improves readability IMO. Guava provides a way to chain Optionals:

    import com.google.common.base.Optional;
    
    Optional resultOpt = s.find1().or(s.find2()).or(s.find3());
    

    It could be another alternative for your problem but does not use the standard Optional class in the JDK.

    If you want to keep the standard API, you could write a simple utility method:

    static  Optional or(Optional first, Optional second) {
        return first.isPresent() ? first : second;
    }
    

    and then:

    Optional resultOpt = or(s.find1(), or(s.find2(), s.find3()));
    

    If you have a lot of optionals to chains, maybe it's better to use the Stream approach as other mentionned already.

提交回复
热议问题