I have this piece of code:
public LatLng[] locationDtoListToLatLngArray(List<LocationDto> locationDtoList) {
return locationDtoList.stream()
.map(locationDto -> new LatLng(locationDto.getLatitude(), locationDto.getLongitude()))
.toArray(LatLng[]::new);
}
but is crashing if locationDto is null inside .map
I fixed it doing this:
public LatLng[] locationDtoListToLatLngArray(List<LocationDto> locationDtoList) {
return locationDtoList.stream()
.map(locationDto -> locationDto == null ? null : new LatLng(locationDto.getLatitude(), locationDto.getLongitude()))
.toArray(LatLng[]::new);
}
but I want to know if there is a better approach (without checking if locationDto == null)
Please note that, if locationDto == null, I want to keep the null, so filter is not an option :)
Thanks
EDIT: I know that the problem is accessing a null object, I just want to know is if there is some function like .map(), that do what I need, .mapKeepingNulls(), something like that.
EDIT 2: I ended up doing this:
public LatLng[] locationDtoListToLatLngArray(List<LocationDto> locationDtoList) {
return locationDtoList.stream()
.map(this::locationDtoToLatLng)
.toArray(LatLng[]::new);
}
private LatLng locationDtoToLatLng(LocationDto locationDto) {
if (locationDto == null) {
return null;
}
return new LatLng(locationDto.getLatitude(), locationDto.getLongitude());
}
null?nulls in the first place in a list? (And I don't think there's a cleaner way, aside from wrapping all of this in anOptional, which would be counterproductive IMO).