柏虎资源网

专注编程学习,Python、Java、C++ 教程、案例及资源

代码优化思路_代码优化思路是什么

判空代码怎么优化的方式

  if (ObjectUtils.isNotEmpty(brandConfigVoList)){
//            for (BrandConfigVo brandConfigVo : brandConfigVoList) {
//                String color = brandConfigVo.getColor();
//                String power = brandConfigVo.getPower();
//                if (StringUtils.isNotBlank(color)) {
//                    String[] splitColor = color.split(",");
//                    if (ObjectUtils.isNotEmpty(splitColor) && splitColor.length >0){
//                        for (String s : splitColor) {
//                            colors.add(s);
//                        }
//                    }
//                }
//                if (StringUtils.isNotBlank(power)) {
//                    String[] splitPower = power.split(",");
//                    if (ObjectUtils.isNotEmpty(splitPower) && splitPower.length >0){
//                        for (String s : splitPower) {
//                            powers.add(s);
//                        }
//                    }
//                }
//                List<String> colorsCollect = colors.stream().distinct().collect(Collectors.toList());
//                brandConfigVo.setColors(colorsCollect);
//                List<String> powersCollect = powers.stream().distinct().collect(Collectors.toList());
//                brandConfigVo.setPowers(powersCollect);
//            }
//        }

读代码

for循环

判断属性值

加分割字符的方式

是否为空的方式

无法使用stream

实现思路

power.split(",") 无法使用stream的方式 因为是一个数组的方式

解决方式

 Arrays.stream(power.split(",")) 继续可以使用stream的方式

解决代码冗余

之前代码

获取颜色属性

判断是否为空

进行分割

判断是否为空 (优化点)

for循环

添加到对象中(优化点)

  String color = brandConfigVo.getColor();
//                String power = brandConfigVo.getPower();
//                if (StringUtils.isNotBlank(color)) {
//                    String[] splitColor = color.split(",");
//                    if (ObjectUtils.isNotEmpty(splitColor) && splitColor.length >0){
//                        for (String s : splitColor) {
//                            colors.add(s);
//                        }
//                    }
//                }

在里面分割完成直接返回

添加到属性中

if (StringUtils.isNotBlank(power)){
    List<String> collect = Arrays.stream(power.split(","))
            .map(String::trim)
            .filter(StringUtils::isNotBlank)
            .distinct()
            .collect(Collectors.toList());
    return collect;
}

总结

判断空和是否创建对象的方式,stream通过流的方式进行操作,我们可以直接复制对象,不用类重复创建对象的方式

之前的想法通过options解决空的问题

Optional.ofNullable(brandConfigVoList)
        .map(brandConfigVos -> {
            brandConfigVos.stream().map(brandConfigVo -> {
            })
        })

通过option的方式只会让代码更加复杂

不会让代码更加简单的方式

我们实现就是让代码更加简单

只能通过stream的方式

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言