Chaining Optionals in Java 8

前端 未结 5 965
刺人心
刺人心 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:14

    Maybe one of

        public  Optional firstOf(Optional first, @SuppressWarnings("unchecked") Supplier>... supp) {
            if (first.isPresent()) return first;
            for (Supplier> sup : supp) {
                Optional opt = sup.get();
                if (opt.isPresent()) {
                    return opt;
                }
            }
            return Optional.empty();
        }
    
        public  Optional firstOf(Optional first, Stream>> supp) {
            if (first.isPresent()) return first;
            Stream> present = supp.map(Supplier::get).filter(Optional::isPresent);
            return present.findFirst().orElseGet(Optional::empty);
        }
    

    will do.

    The first one iterates over an array of suppliers. The first non-empty Optional<> is returned. If we don't find one, we return an empty Optional.

    The second one does the same with a Stream of Suppliers which is traversed, each one asked (lazily) for their value, which is then filtered for empty Optionals. The first non-empty one is returned, or if no such exists, an empty one.

提交回复
热议问题