我有一个包含一些属性的类,如果值不为空,我想连接该属性。优雅的方法是什么?到目前为止我所做的是这样的(在 combine
方法中)。
public class X {
private String a;
private String b;
private String c;
private String d;
private String e;
private int f;
private Date g;
public String combine() {
String result = "";
if (!StringUtils.isEmpty(this.a)) {
result += a + "\n";
}
if (!StringUtils.isEmpty(this.b)) {
result += b + "\n";
}
if (!StringUtils.isEmpty(this.c)) {
result += c + "\n";
}
if (!StringUtils.isEmpty(this.d)) {
result += d + "\n";
}
if (!StringUtils.isEmpty(this.e)) {
result += e + "\n";
}
return result;
}
}
最佳答案
您可以使用 java-8 stream
在 toString
方法中执行此操作
Stream.of(this.getA(),this.getB(),this.getC(),this.getD(),this.getE())
.filter(str->!StringUtils.isEmpty(str))
.collect(Collectors.joining("\n"));
或者您可以使用 StringUtils。 isNotEmpty
Stream.of(this.getA(),this.getB(),this.getC(),this.getD(),this.getE())
.filter(StringUtils::isNotEmpty)
.collect(Collectors.joining("\n"));
关于java - 附加非空字符串的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58610494/