Chaining Optionals in Java 8

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

    Use a Stream:

    Stream.of(find1(), find2(), find3())
        .filter(Optional::isPresent)
        .map(Optional::get)
        .findFirst();
    

    If you need to evaluate the find methods lazily, use supplier functions:

    Stream.of(this::find1, this::find2, this::find3)
        .map(Supplier::get)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .findFirst();
    

提交回复
热议问题