英文:
Check for null List from Rest endpoint
问题
我在Spring Rest终端接收到这个DTO:
public class RequestDTO {
private List<Integer> additionalImages;
}
我想检查列表,如果它不为null,就进行一些迭代:
List<Integer> additionalImages = dto.getAdditionalImages();
if (additionalImages != null && !additionalImages.isEmpty()) {
for (int i = 0; i < additionalImages.size(); i++) {
ProductImages pi = new ProductImages();
pi.setProductId(result.getId());
pi.setAdditionalImages(additionalImages.get(i));
productImagesService.save(pi);
}
}
请问,如何正确进行这种检查?我在这里获得了NPE(NullPointerException):additionalImages.size()
。
英文:
I receive this DTO in Spring Rest Endpoint:
public class RequestDTO {
private List<Integer> additionalImages;
}
I want check the list and do some iterations if it's not null:
List<Integer> additionalImages = dto.getAdditionalImages();
if(additionalImages != null || !additionalImages.isEmpty())
{
for(int i = 0; i < additionalImages.size(); i++){
ProductImages pi = new ProductImages();
pi.setProductId(result.getId());
pi.setAdditionalImages(i);
productImagesService.save(pi);
}
}
What is the proper way to do this check? I get NPE here additionalImages.size()
.
答案1
得分: 2
你可以使用 Streams
遍历列表并创建所需的对象。最好先创建所有的 ProductImage
,然后一次性保存它们。
public void foo() {
List<ProductImage> productImages = createProductImages(dto.getAdditionalImages());
productImagesService.saveAll(productImages);
}
public List<ProductImage> createProductImages(List<Integer> additionalImages) {
return Optional.ofNullable(additionalImages).orElse(Collections.emptyList()).stream()
.map(i -> {
ProductImage productImage = new ProductImage();
productImage.setProductId(result.getId());
productImage.setAdditionalImage(i);
return productImage;
}).collect(Collectors.toList());
}
英文:
You can use Streams
to iterate over the list and create required objects. It's better to create all ProductImage
first and then save them all at once.
public void foo() {
List<ProductImage> productImages = createProductImages(dto.getAdditionalImages());
productImagesService.saveAll(productImages);
}
public List<ProductImage> createProductImages(List<Integer> additionalImages) {
return Optional.ofNullable(additionalImages).orElse(Collections.emptyList()).stream()
.map(i -> {
ProductImage productImage = new ProductImage();
productImage.setProductId(result.getId);
productImage.setAdditionalImage(i);
return productImage;
}).collect(Collectors.toList());
}
答案2
得分: 1
-
additionalImages.isEmpty
是多余的 - 如果列表为空,for循环将被跳过,因此您可以简化if语句。 -
检查“非null或非空”将同时检查两个条件,因此NPE实际上应该存在,而不是大小检查。
英文:
-
additionalImages.isEmpty
is redundant - the for loop will be skipped if the list is empty, so, you can simplify the if statement -
Checking "not null or not empty" will check both conditions, so the NPE should actually be there, not the size check.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论