如何在Java中将null值替换为空字符串?

12

我从数据库中获取了null值,但需要显示空字符串""


例如,我必须将四个值附加到Excel表格的单个单元格中,如下所示:

sheet.addCell(new Label(4, currentRow, a.getPar()+" "+a.getO()+" "+a.getPar()));

如何在Java中实现预期结果(替换)?

请发布一些你的代码... - vikingsteve
3
你可以使用Apache commons的StringUtils来处理这个:http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#defaultString%28java.lang.String%29。 - Marco Forberg
2
尝试使用com.google.common.base.Strings.nullToEmpty()函数。 - Ilya Serbis
5
这难道不是一个问题吗?如果你想避免空值检查并且必须处理旧的API,使用Strings.nullToEmpty(s)会使代码更清晰、更好,而不是用三元运算符使代码变得混乱。 - Alexander Oh
1
所有好的答案都在这里:https://dev59.com/RWEh5IYBdhLWcg3w3mqK - Vadzim
显示剩余2条评论
2个回答

32

如果我理解正确,你可以使用三元操作符:

System.out.println("My string is: " + ((string == null) ? "" : string));

如果您不熟悉它,它的意思是“字符串是否为空? 如果是,则返回空字符串,否则返回该字符串”。我说“返回”,因为您可以将((string == null) ? "" : string)视为返回String的函数。

当然,您可以将空字符串替换为任何其他String


我需要同时检查四个字符串的空值,并将其显示在Excel表格中。 - user2408111
a.getParan() 替换 string,然后可能用 a.getO() - Djon
同样适用于JSP表达式。 - Ujjwal Singh

15

如果我理解正确,您需要这个。

public static String replaceNull(String input) {
  return input == null ? "" : input;
}

并在需要的任何地方使用它,例如

sheet.addCell(new Label(4,currentRow, replaceNull(a.getParan())+" "+replaceNull(a.getO())+" "+replaceNull(a.getParan())));

希望这能有所帮助


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接