我收到一份模型列表。模型的数量可能很大。这个模型有一堆属性,其中任何一个都可能是null。
我需要根据模型的属性为每个模型构建一个字符串。如果 property == null,那么我会在结果字符串中添加一些静态部分,例如 "property1 is null"。
如果 else property != null 然后我添加类似这样的内容 "property1 == 'valueOfThePropertyHere'"。
结果字符串应该是这样的:
prop1 == 'value1' and prop2 is null and prop3 == 'value3' and prop4 == 'value4' and prop5 is null and ..... propN == 'valueN'
然后我为列表中的每个模型生成这样的字符串。
显然,我在 for 循环中执行此操作,为此我使用 StringBuilder。问题是,在 StringBuilder 的 append 方法中,我使用三元运算符检查模型的每个字段是否为空,并基于此将此检查的结果添加到结果字符串中。但是如果一个属性不为 null 那么我需要添加一些静态部分 + 字段本身的值 + 一些更多的静态内容。这意味着我需要为我拥有的每个属性再添加一个 StringBuilder。或者我可以使用“+”,它无论如何都会被转换成 StringBuilder,据我所知,在 StringBuilder 中使用“+”是一种不好的做法(但我无论如何都必须使用它)。
例子:
List<Model> models = repository.getModels();
for (Model m: models) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder
.append(m.getField1() == null ? "field1 is null" : "field1 == '" + new StringBuiler().append(m.getField1()).append("'").append(" and ").toString()))
.append(m.getField2() == null ? "field2 is null" : "field2 == '" + new StringBuiler().append(m.getField2()).append("'").append(" and ").toString()))
...............
.append(m.getFieldN() == null ? "fieldN is null" : "fieldN == '" + new StringBuiler().append(m.getFieldN()).append("'").append(" and ").toString()));
System.out.println(stringBuilder.toString());
}
在我看来,从性能的角度来看,它看起来不太好,因为对于模型列表中的每个模型,我都在堆中创建了另一组 StringBuilder 对象,只是为了获取结果字符串。
我错过了什么吗?从性能的角度来看,是否有更好的方法来做到这一点?或者没关系,因为我现在看不到其他选项。
最佳答案
追求简单。
代替
stringBuilder
.append(m.getField1() == null ? "field1 is null" : "field1 == '" + new StringBuiler().append(m.getField1()).append("'").append(" and ").toString()))
使用:
if (m.getField1() == null) {
stringBuilder.append("field1 is null");
} else {
stringBuilder.append("field1 == '").append(m.getField1()).append("'").append(" and ");
}
除了在 StringBuilder.append
调用中使用 StringBuilder
的明显奇怪之外(为什么不直接使用 +
呢... ),真的很难解析 :
在条件表达式中的位置。将它分成几行要容易得多。
如果您发现自己不得不多次重复此代码模式,请定义一个方法:
void append(StringBuilder stringBuilder, String name, Object value) {
stringBuilder.append(name);
if (value == null) {
stringBuilder.append(" is null");
} else {
stringBuilder.append(" == '").append(value).append("'").append(" and ");
}
}
然后像这样调用:
append(stringBuilder, "field1", m.getField1());
append(stringBuilder, "field2", m.getField2());
append(stringBuilder, "field3", m.getField3());
关于java - StringBuilder 中的多个 StringBuilder。值得吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58768828/