需求是在数据库查询出所有二级分类下的商品数量存入Map集合,再循环取出每一个二级分类的数量,然后存入List集合返回给前台。在存入List集合时发生空指针错误,排查后发现有些分类下并没有商品,在存的时候就会爆空指针错误,解决办法,做一个判断,如果为空,赋值为0。
代码如下
//获取一二级分类
List<DangDangCategory1> categoryList=categoryService.selectCategory1With2();
//获取二级分类数量
Map<String,Integer> countCategory2Map =category2Service.selectCountCategory2();
//获取一级分类的数量
Map<String,Integer> countCategory1Map=categoryService.selectCountCategory1();
//全部数量
int totalCategoryCount=0;
//循环categoryList 通过分类id查找 完成存入数量
for(DangDangCategory1 category1:categoryList){
String category1Id=String.valueOf(category1.getCategory1Id());//一级分类的id
//取出id对应的数量
Integer count1 =countCategory1Map.get(category1Id);
//判断数量是否为空
if(count1==null){
count1=0;