还能优化吗
时间: 2023-07-20 22:23:15 浏览: 75
可以继续优化,将字符串替换的操作和字符串拼接的操作合并成一个方法,避免了重复的代码和字符串拼接带来的性能损耗。以下是优化后的代码:
```java
StringBuilder conceptForm = new StringBuilder("<p > & nbsp; 您选择的保险计划为:</p >");
for (int i = 0; i < conceptForms.size(); i++) {
NameAndConceptForm nameAndConceptForm = conceptForms.get(i);
List<ConceptAndAmountForm> conceptAndAmountForms = nameAndConceptForm.getConceptAndAmountForms();
String name = nameAndConceptForm.getName();
if (StringUtils.isNotBlank(name)) {
replaceAndAppend(conceptForm, "<p> 被保险人姓名:@被保人姓名@</p>", "@被保人姓名@", name);
}
for (int j = 0; j < conceptAndAmountForms.size(); j++) {
ConceptAndAmountForm conceptAndAmountForm = conceptAndAmountForms.get(j);
String selfAmount = conceptAndAmountForm.getSelfAmount();
String supportConcept = conceptAndAmountForm.getSupportConcept();
if (StringUtils.isNotBlank(selfAmount)) {
replaceAndAppend(conceptForm, "<p> 投保计划:@保障方案@,员工自费@计划金额@元/年</p>", "@保障方案@", selfAmount);
replaceAndAppend(conceptForm, "@计划金额@", supportConcept);
}
}
}
content = content.replace("@计划模板@", conceptForm.toString());
private static void replaceAndAppend(StringBuilder stringBuilder, String template, String placeholder, String replacement) {
int index = stringBuilder.indexOf(placeholder);
if (index >= 0) {
stringBuilder.replace(index, index + placeholder.length(), replacement);
stringBuilder.append(template, index + replacement.length() - placeholder.length(), template.length() - placeholder.length());
}
}
private static void replaceAndAppend(StringBuilder stringBuilder, String template, String placeholder) {
int index = stringBuilder.indexOf(placeholder);
if (index >= 0) {
stringBuilder.replace(index, index + placeholder.length(), "");
stringBuilder.append(template, index, template.length());
}
}
```
`replaceAndAppend` 方法用于替换占位符并将字符串拼接到 StringBuilder 中,`replaceAndAppend` 方法的第二个参数用于指定占位符,如果占位符为空,则直接将模板拼接到 StringBuilder 中。这样可以避免重复的代码和字符串拼接带来的性能损耗。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)