gpt4 book ai didi

Java 8 流映射,将空值保留为空值

转载 作者:行者123 更新时间:2023-11-30 08:34:57 26 4
gpt4 key购买 nike

我有这段代码:

public LatLng[] locationDtoListToLatLngArray(List<LocationDto> locationDtoList) {
return locationDtoList.stream()
.map(locationDto -> new LatLng(locationDto.getLatitude(), locationDto.getLongitude()))
.toArray(LatLng[]::new);
}

但是如果 locationDto.map 中为 null 则崩溃

我修复了它:

public LatLng[] locationDtoListToLatLngArray(List<LocationDto> locationDtoList) {
return locationDtoList.stream()
.map(locationDto -> locationDto == null ? null : new LatLng(locationDto.getLatitude(), locationDto.getLongitude()))
.toArray(LatLng[]::new);
}

但我想知道是否有更好的方法(不检查是否 locationDto == null)

请注意,如果 locationDto == null,我想保留 null,所以过滤器不是一个选项:)

谢谢

编辑:我知道问题出在访问空对象上,我只想知道是否有像 .map() 这样的函数可以满足我的需要,。 mapKeepingNulls(),类似的东西。

编辑 2:我最终这样做了:

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 值的方法。如果你真的不想在那里进行空检查(我认为这是一个很好的解决方案),你可以尝试在 LatLng 中创建一个静态方法,它将采用 LocationDto 并返回当提供的 LocationDtonull 时,正确的实例或 null

像这样:

public static LatLng getFromLocationDto(LocationDto ldt){
if(ldt == null)
return null;

return new LatLng(ldt.getLatitude(), ldt.getLongitude());
}

但是 null 检查必须在某个地方(除非您可以确保 locationDtoList 中没有 null)。

关于Java 8 流映射,将空值保留为空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38546629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com