gpt4 book ai didi

java - 附加非空字符串的优雅方式

转载 作者:行者123 更新时间:2023-11-29 08:20:54 25 4
gpt4 key购买 nike

我有一个包含一些属性的类,如果值不为空,我想连接该属性。优雅的方法是什么?到目前为止我所做的是这样的(在 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 streamtoString 方法中执行此操作

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com