在dto to bean转换中,
我尝试仅在bean中找不到dto时才添加dto ...或者如果dto的id为null
我使用没有匹配的流.
当我尝试添加许多汽车时,只添加第一个
List<Car> cars = bean.getCar();
List<CarDto> carsDto = dto.getCar();
for (CarDto carDto : carsDto) {
if (cars.stream().noneMatch(e -> Objects.equals(e.getId(), carDto.getId()) || carDto.getId()==null )) {
//get car from bd....
bean.addCar(car);
}
}
Run Code Online (Sandbox Code Playgroud)
将条件carDto.getId()==null置于其中noneMatch将阻止您获取CarDto具有null id的条件.
您可以将其更改为
if (carDto.getId() == null
|| cars
.stream()
.noneMatch(e -> Objects.equals(e.getId(), carDto.getId())))
Run Code Online (Sandbox Code Playgroud)
更新:
感谢Holger @对于这个建议:你可以将第二个if条件简化为(并且不需要使用,Objects.equals因为carDto.getId不能为null.
cars.stream()
.map(Car::getId)
.noneMatch(carDto.getId()::equals)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
329 次 |
| 最近记录: |