代码优化思路

发布时间:2025-09-08 19:43  浏览量:24

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);// }// }// }// ListcolorsCollect = colors.stream.distinct.collect(Collectors.toList); // brandConfigVo.setColors(colorsCollect); // ListpowersCollect = powers.stream.distinct.collect(Collectors.toList); // brandConfigVo.setPowers(powersCollect); // } // }

for循环

判断属性值

加分割字符的方式

是否为空的方式

实现思路

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)){Listcollect = 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的方式