Reputation: 9150
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());
}
Upvotes: 2
Views: 1309
Reputation: 3682
You can make use of Optional, which is a new class in Java 8 made for this purpose.
// transform locationDtoList to a list of Optional
locationDtoList.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.map(locationDto -> new LatLng(locationDto.getLatitude(), locationDto.getLongitude()))
.toArray(LatLng[]::new);
Upvotes: 0
Reputation: 1756
The issue as little to do with Java 8 streams. You are getting an NullPointerException
when doing locationDto.getLatitude()
.
It is totally normal to check for null value. If you were not in a stream, I am almost sure that you would have not disturbed you.
Maybe what you dislike is the fact that you are performing inline conditional operation in a one-liner, in which case I advise you to use an helper function like _createLatLng(LocationDto locationDto)
to externalize that process.
Upvotes: 0
Reputation: 166
The problem is that you are accessing methods of a potentionally null
value. If you really don't want the null check there (which I think is a good solution) you can try making a static method in LatLng
that will take the LocationDto
and return the right instance or null
when the supplied LocationDto
is null
.
Something like this:
public static LatLng getFromLocationDto(LocationDto ldt){
if(ldt == null)
return null;
return new LatLng(ldt.getLatitude(), ldt.getLongitude());
}
But the null
check has to be somewhere (unless you can ensure that there will be no null
int the locationDtoList
).
Upvotes: 2