I'm having trouble making my method null-safe using streams and flatMap..
My input is a List<RequestSlot>
And the objects are nested as such:
Request
OuterItem
List<InnerItem>
This is working to flatten the lists and create one List, but I'm unsure how to add Optionals here to make this null safe for each map/stream step.
final List<InnerItem> innerItem = request.stream()
.map(RequestSlot::getOuterItem)
.flatMap(outerItem -> outerItem.getInnerItem().stream()).collect(Collectors.toList());
I have tried using Stream.ofNullable but that ends up creating a stream that I'm unsure how to then collect. Any pointers?
You don't actually need to use
Optional. Justfilter(Objects:nonNull)everywhere after mapping to something that might be null. This filters out all the null thingsIf you really want to use
Stream.ofNullable, use the patternflatMap(x -> Stream.ofNullable(x.getX()))(wheregetXmight return null).