I wonder what's teh best approach to check if list is null. In my Stream I call orElseThrow
twice. It works but I don;t know if its correct? It looks a little bit ugly:
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"));
I have to throw error when list is null and when no item was found
CodePudding user response:
Just check if the list is null directly. Streaming elements from a list only makes sense if the list exists in the first place.
if(null != listCanBeNull) {
// stream things from here
}
CodePudding user response:
An Optional.ofNullable can be turned into a (possibly empty) Stream, or you can immediately use Stream.ofNullable. And do a flatMap.
Stream.ofNullable(listCanBeNull)
.stream()
.flatMap()
.filter(configuration -> couration.getId().equals(warehouseConfigurationId))
.findAny()
.orElseThrow(() -> new ResourceNotFoundException("the same error message"));