for (CommodityVO good : goods) { StringBuilder name = new StringBuilder(good.getName()); if (StringUtil.isNotBlank(good.getData()) || StringUtil.isNotBlank(good.getAttribute()) || StringUtil.isNotBlank(good.getMaterial())){ name.append("("); } if ((StringUtil.isNotBlank(good.getData()) && StringUtil.isNotBlank(good.getAttribute())) || (StringUtil.isNotBlank(good.getData()) && StringUtil.isNotBlank(good.getMaterial()))) { name.append(good.getData()).append("、"); }else{ name.append(good.getData()); } if (StringUtil.isNotBlank(good.getAttribute()) && StringUtil.isNotBlank(good.getMaterial())) { name.append(good.getAttribute()).append("、"); }else { name.append(good.getAttribute()); } if (StringUtil.isNotBlank(good.getMaterial())) { String[] list = good.getMaterial().split(","); if (list.length > 1){ String join = String.join("/", list); name.append(join); }else { name.append(good.getMaterial()); } } if (StringUtil.isNotBlank(good.getData()) || StringUtil.isNotBlank(good.getAttribute()) || StringUtil.isNotBlank(good.getMaterial())){ name.append(")"); } if (!ObjectUtil.isEmpty(good.getVipMoney())) { good.setMoney(good.getVipMoney()); }}怎么优化更简洁
时间: 2024-02-24 21:00:31 浏览: 68
可以使用 Java 8 的 Stream API 和 Lambda 表达式来简化代码,如下所示:
```
goods.forEach(good -> {
StringBuilder name = new StringBuilder(good.getName());
if (Stream.of(good.getData(), good.getAttribute(), good.getMaterial()).anyMatch(StringUtil::isNotBlank)) {
name.append("(");
}
if (StringUtil.isNotBlank(good.getData())) {
name.append(good.getData());
if (StringUtil.isNotBlank(good.getAttribute()) || StringUtil.isNotBlank(good.getMaterial())) {
name.append("、");
}
}
if (StringUtil.isNotBlank(good.getAttribute())) {
name.append(good.getAttribute());
if (StringUtil.isNotBlank(good.getMaterial())) {
name.append("、");
}
}
if (StringUtil.isNotBlank(good.getMaterial())) {
String[] list = good.getMaterial().split(",");
if (list.length > 1) {
name.append(String.join("/", list));
} else {
name.append(good.getMaterial());
}
}
if (Stream.of(good.getData(), good.getAttribute(), good.getMaterial()).anyMatch(StringUtil::isNotBlank)) {
name.append(")");
}
if (!ObjectUtil.isEmpty(good.getVipMoney())) {
good.setMoney(good.getVipMoney());
}
});
```
使用 Stream API 和 Lambda 表达式可以使代码更加简洁易读,同时还可以提高代码的运行效率。
阅读全文