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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With