Java Streams - 检查列表是否为空

Mat*_*ley 0 java java-stream

我想知道检查列表是否为空的最佳方法是什么。在我的直播中,我拨打了orElseThrow两次电话。它有效,但我不知道它是否正确?看起来有点难看:

Optional.ofNullable(listCanBeNull)
                .orElseThrow(() -> new ResourceNotFoundException("the same error message"))
                .stream()
                .filter(configuration -> configuration.getId().equals(warehouseConfigurationId))
                .findAny()
                .orElseThrow(() -> new ResourceNotFoundException("the same error message"));
Run Code Online (Sandbox Code Playgroud)

当列表为空且未找到任何项目时,我必须抛出错误

Mak*_*oto 5

直接检查列表是否为空即可。仅当列表首先存在时,从列表中流式传输元素才有意义。

if(null != listCanBeNull) {
    // stream things from here
}
Run Code Online (Sandbox Code Playgroud)