Chaining Optionals in Java 8

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

    To perform Optional Chaining First convert Stream to Optional Using either of the two methods

    1. findAny() or findFirst()
    2. min() / max()

    Once optional is obtained optional has two more instance method which are also present in Stream class i.e filter and map(). use these on methods and to check output use ifPresent(System.out :: Println)

    ex:

    Stream s = Stream.of(1,2,3,4);

    s.findFirst().filter((a)->a+1).ifPresent(System.out :: Println)

    Output is : 2

提交回复
热议问题