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
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)
.flatMap(List::stream)
.filter(configuration -> configuration.getId().equals(warehouseConfigurationId))
.findAny()
.orElseThrow(() -> new ResourceNotFoundException("the same error message"));