Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert single element list to java 8 optional

Tags:

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));
like image 798
MariuszS Avatar asked Jun 16 '15 12:06

MariuszS


1 Answers

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.

like image 93
Konstantin Yovkov Avatar answered Oct 21 '22 08:10

Konstantin Yovkov