How to convert single element list to java 8 optional

十年热恋 提交于 2019-12-06 17:27:49

问题


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.



来源:https://stackoverflow.com/questions/30868069/how-to-convert-single-element-list-to-java-8-optional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!