How to convert single element list to java 8 optio

2020-08-09 08:24发布

问题:

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));

回答1:

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.