简体   繁体   中英

How to convert single element list to java 8 optional

How to nicely convert list containing one or zero elements to Optional?

The ugly code:

List<Integer> integers = new ArrayList<>();

Optional<Integer> optional = integers.size() == 0 ?
        Optional.empty() :
        Optional.of(integers.get(0));

You can use the Stream#findFirst() method, which:

Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.

List<Integer> list = ...
Optional<Integer> optional = list.stream().findFirst();

Alternatively, with the same success you can also use the Stream#findAny() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM