大后端-番外篇-01 Java 常用方法总结

一、集合遍历

集合遍历有多种方法,一种是 foreach遍历,另一个是直接使用 map 遍历,一般高逼端的程序员都使用map遍历。

map集合遍历

@Override
    public void saveImages(Long id, List<String> images){
        if(images == null || images.size() == 0 || id < 0){

        }else{
         List<SpuImagesEntity> collect = images.stream().map(img ->{
              SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
              spuImagesEntity.setId(id);
              spuImagesEntity.setImgUrl(img);

              return spuImagesEntity;
            }).collect(Collectors.toList());

         this.saveBatch(collect);
        }
    }

二、对象属性赋值

获取一个对象,需要把这个对象的值复制到另外一个实体对象类,那木,如果两者的属性字段一样,则可以使用 BeanUtils.copyProperties(vo,infoEntity); 方法来处理,而不用一个一个做映射对照set来处理。

/**
     * //TODO 高级部分完善
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();

                // 复制vo的属性字段值到 infoEntity对象
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);
}

三、集合过滤

List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrlistforspu(spuId);

Set<Long> idSet = new HashSet<>(searchAttrIds);
baseAttrs.stream().filter(item ->{
      return idSet.contains(item.getAttrId());   
}).collect(Collectors.toList());

四、集合先过滤然后再遍历处理

先对每个数据进行过滤,然后在对每个数据进行封装,最后再收集起来,这个是更高级的用法:

List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrlistforspu(spuId);

 List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item ->{
            return idSet.contains(item.getAttrId());
        }).map(item->{
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

五、集合混合处理

Stream在java中我们经常称为『流』,我们会用流去对集合进行一些流水线的操作,stream就像工厂一样,我们只需要把集合和命令还有一些参数灌输到流水线中去,最终加工成我们想要的结果。

原集合 —> 流  —> 各种操作(过滤、分组、统计) —> 终端操作

Stream流的操作流程一般都是这样的,先将集合转为流,然后经过各种操作,比如过滤、筛选、分组、计算。最后的终端操作,就是转化成我们想要的数据,一般还是集合,有的时候我们想变成count计数,后面我们会一一举例

file

项目实战代码:
gulimall-product/src/main/java/com/atguigu/gulimall/product/service/impl/CategoryServiceImpl.java

@Override
  public Map<String, List<Catelog2Vo>> getCatalogJson() {
    // 1、查出所有1级分类
    List<CategoryEntity> level1Categorys = getLevel1Categorys();

    // 2、封装数据
    Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k->k.getCatId().toString(),
        v->{
          // 每一个的一级分类,查到这个一级分类的二级分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));

          // 封装上面的结果
          List<Catelog2Vo> catelog2Vos = null;
          if(categoryEntities != null){
            catelog2Vos = categoryEntities.stream().map(l2 ->{
              Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

              // 找二级分类的三级分类
              List<CategoryEntity> level3Catelog = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));

              if(level3Catelog != null){
               List<Catelog2Vo.Catelog3Vo> catelog3vos = level3Catelog.stream().map(l3 ->{
                  // 封装成指定格式
                  Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                  return catelog3Vo;
                }).collect(Collectors.toList());

                catelog2Vo.setCatalog3List(catelog3vos);
              }

              return catelog2Vo;
          }).collect(Collectors.toList());
        }

          return catelog2Vos;
        }));

    return parent_cid;

  }

返回响应结果结构:

[
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "1",
                "id": "1",
                "name": "电子书"
            },
            {
                "catalog2Id": "1",
                "id": "2",
                "name": "网络原创"
            },
            {
                "catalog2Id": "1",
                "id": "3",
                "name": "数字杂志"
            },
            {
                "catalog2Id": "1",
                "id": "4",
                "name": "多媒体图书"
            }
        ],
        "id": "1",
        "name": "电子书刊"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "2",
                "id": "5",
                "name": "音乐"
            },
            {
                "catalog2Id": "2",
                "id": "6",
                "name": "影视"
            },
            {
                "catalog2Id": "2",
                "id": "7",
                "name": "教育音像"
            }
        ],
        "id": "2",
        "name": "音像"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "3",
                "id": "8",
                "name": "少儿"
            },
            {
                "catalog2Id": "3",
                "id": "9",
                "name": "商务投资"
            },
            {
                "catalog2Id": "3",
                "id": "10",
                "name": "英语学习与考试"
            },
            {
                "catalog2Id": "3",
                "id": "11",
                "name": "文学"
            },
            {
                "catalog2Id": "3",
                "id": "12",
                "name": "传记"
            },
            {
                "catalog2Id": "3",
                "id": "13",
                "name": "励志"
            }
        ],
        "id": "3",
        "name": "英文原版"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "4",
                "id": "14",
                "name": "小说"
            },
            {
                "catalog2Id": "4",
                "id": "15",
                "name": "文学"
            },
            {
                "catalog2Id": "4",
                "id": "16",
                "name": "青春文学"
            },
            {
                "catalog2Id": "4",
                "id": "17",
                "name": "传记"
            },
            {
                "catalog2Id": "4",
                "id": "18",
                "name": "艺术"
            }
        ],
        "id": "4",
        "name": "文艺"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "5",
                "id": "19",
                "name": "少儿"
            },
            {
                "catalog2Id": "5",
                "id": "20",
                "name": "0-2岁"
            },
            {
                "catalog2Id": "5",
                "id": "21",
                "name": "3-6岁"
            },
            {
                "catalog2Id": "5",
                "id": "22",
                "name": "7-10岁"
            },
            {
                "catalog2Id": "5",
                "id": "23",
                "name": "11-14岁"
            }
        ],
        "id": "5",
        "name": "少儿"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "6",
                "id": "24",
                "name": "历史"
            },
            {
                "catalog2Id": "6",
                "id": "25",
                "name": "哲学"
            },
            {
                "catalog2Id": "6",
                "id": "26",
                "name": "国学"
            },
            {
                "catalog2Id": "6",
                "id": "27",
                "name": "政治/军事"
            },
            {
                "catalog2Id": "6",
                "id": "28",
                "name": "法律"
            },
            {
                "catalog2Id": "6",
                "id": "29",
                "name": "人文社科"
            },
            {
                "catalog2Id": "6",
                "id": "30",
                "name": "心理学"
            },
            {
                "catalog2Id": "6",
                "id": "31",
                "name": "文化"
            },
            {
                "catalog2Id": "6",
                "id": "32",
                "name": "社会科学"
            }
        ],
        "id": "6",
        "name": "人文社科"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "7",
                "id": "33",
                "name": "经济"
            },
            {
                "catalog2Id": "7",
                "id": "34",
                "name": "金融与投资"
            },
            {
                "catalog2Id": "7",
                "id": "35",
                "name": "管理"
            },
            {
                "catalog2Id": "7",
                "id": "36",
                "name": "励志与成功"
            }
        ],
        "id": "7",
        "name": "经管励志"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "8",
                "id": "37",
                "name": "生活"
            },
            {
                "catalog2Id": "8",
                "id": "38",
                "name": "健身与保健"
            },
            {
                "catalog2Id": "8",
                "id": "39",
                "name": "家庭与育儿"
            },
            {
                "catalog2Id": "8",
                "id": "40",
                "name": "旅游"
            },
            {
                "catalog2Id": "8",
                "id": "41",
                "name": "烹饪美食"
            }
        ],
        "id": "8",
        "name": "生活"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "9",
                "id": "42",
                "name": "工业技术"
            },
            {
                "catalog2Id": "9",
                "id": "43",
                "name": "科普读物"
            },
            {
                "catalog2Id": "9",
                "id": "44",
                "name": "建筑"
            },
            {
                "catalog2Id": "9",
                "id": "45",
                "name": "医学"
            },
            {
                "catalog2Id": "9",
                "id": "46",
                "name": "科学与自然"
            },
            {
                "catalog2Id": "9",
                "id": "47",
                "name": "计算机与互联网"
            },
            {
                "catalog2Id": "9",
                "id": "48",
                "name": "电子通信"
            }
        ],
        "id": "9",
        "name": "科技"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "10",
                "id": "49",
                "name": "中小学教辅"
            },
            {
                "catalog2Id": "10",
                "id": "50",
                "name": "教育与考试"
            },
            {
                "catalog2Id": "10",
                "id": "51",
                "name": "外语学习"
            },
            {
                "catalog2Id": "10",
                "id": "52",
                "name": "大中专教材"
            },
            {
                "catalog2Id": "10",
                "id": "53",
                "name": "字典词典"
            }
        ],
        "id": "10",
        "name": "教育"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "11",
                "id": "54",
                "name": "艺术/设计/收藏"
            },
            {
                "catalog2Id": "11",
                "id": "55",
                "name": "经济管理"
            },
            {
                "catalog2Id": "11",
                "id": "56",
                "name": "文化/学术"
            },
            {
                "catalog2Id": "11",
                "id": "57",
                "name": "少儿"
            }
        ],
        "id": "11",
        "name": "港台图书"
    },
    {
        "catalog1Id": "1",
        "catalog3List": [
            {
                "catalog2Id": "12",
                "id": "58",
                "name": "工具书"
            },
            {
                "catalog2Id": "12",
                "id": "59",
                "name": "杂志/期刊"
            },
            {
                "catalog2Id": "12",
                "id": "60",
                "name": "套装书"
            }
        ],
        "id": "12",
        "name": "其他"
    }
]

六、使用IDEA抽取方法

有时候代码的一个方法中写了很多不同的业务,导致整个方法代码量很多,很难查看,这个时候就需要人工将部分逻辑抽出来,直接封装一个方法,然后在这个方法中调用即可,可以大大提高代码的可读性。以前笨办法是直接复制上边的代码到一个新方法中,现在可以使用IDEA功能直接抽取方法。

业务代码:

@Override
  public Map<String, List<Catelog2Vo>> getCatalogJson() {

      // 将数据库的多次查询变为一次
    List<CategoryEntity> selectList = baseMapper.selectList(null);

    // 1、查出所有1级分类
    List<CategoryEntity> level1Categorys = getLevel1Categorys();

    // 2、封装数据
    Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k->k.getCatId().toString(),
        v->{
          // 每一个的一级分类,查到这个一级分类的二级分类
          List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));

          // 封装上面的结果
          List<Catelog2Vo> catelog2Vos = null;
          if(categoryEntities != null){
            catelog2Vos = categoryEntities.stream().map(l2 ->{
              Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

              // 找二级分类的三级分类
              List<CategoryEntity> level3Catelog = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));

              if(level3Catelog != null){
                List<Catelog2Vo.Catelog3Vo> catelog3vos = level3Catelog.stream().map(l3 ->{
                  // 封装成指定格式
                  Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                  return catelog3Vo;
                }).collect(Collectors.toList());

                catelog2Vo.setCatalog3List(catelog3vos);
              }

              return catelog2Vo;
            }).collect(Collectors.toList());
          }

          return catelog2Vos;
        }));

    return parent_cid;

  }

抽取方法步骤:
file

file

自动替换之后的方法:

@Override
  public Map<String, List<Catelog2Vo>> getCatalogJson() {

      // 将数据库的多次查询变为一次
    List<CategoryEntity> selectList = baseMapper.selectList(null);

    // 1、查出所有1级分类
    List<CategoryEntity> level1Categorys = getLevel1Categorys();

    // 2、封装数据
    Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k->k.getCatId().toString(),
        v->{
          // 每一个的一级分类,查到这个一级分类的二级分类
          List<CategoryEntity> categoryEntities = getParent_cid(v);

          // 封装上面的结果
          List<Catelog2Vo> catelog2Vos = null;
          if(categoryEntities != null){
            catelog2Vos = categoryEntities.stream().map(l2 ->{
              Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

              // 找二级分类的三级分类
              List<CategoryEntity> level3Catelog = getParent_cid(l2);

              if(level3Catelog != null){
                List<Catelog2Vo.Catelog3Vo> catelog3vos = level3Catelog.stream().map(l3 ->{
                  // 封装成指定格式
                  Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                  return catelog3Vo;
                }).collect(Collectors.toList());

                catelog2Vo.setCatalog3List(catelog3vos);
              }

              return catelog2Vo;
            }).collect(Collectors.toList());
          }

          return catelog2Vos;
        }));

    return parent_cid;

  }

private List<CategoryEntity> getParent_cid(CategoryEntity v) {
    return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
  }

是不是很强大呢?减少了自己很多的工作量。

七、Mybatis-plus相关

查询条件语句够时间:

 @Override
    public List<SkuImagesEntity> getImagesBySkuId(Long skuId) {

        // 构建查询条件
        QueryWrapper<SkuImagesEntity> queryWrapper = new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId);

        // 查询
        List<SkuImagesEntity> imgs = this.baseMapper.selectList(queryWrapper);
        return imgs;
    }

为者常成,行者常至