且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将单元素列表转换为java 8可选

更新时间:2023-01-24 17:30:48

您可以使用 Stream#findFirst() 方法,其中:

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


返回描述此流的第一个元素的Optional,如果流为空,

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

或者,同样成功,您还可以使用 Stream#findAny() 方法。

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