我又遇到了一个有趣的问题,我需要动态构建包含 IN 条件的 SQL 查询。所以我有 String 列表,我需要将它们插入到我的 StringBuilder
中,用逗号分隔。
所以我的第一个想法是使用一些 boolean 值来确定我是否应该插入昏迷。
builder.append("TABLE.METACODES in (");
boolean isFirst = true;
for(String metaCode : cto.getEntityMetaCodes()) {
if(isFirst) {
isFirst = false;
builder.append("'" + metaCode + "'");
} else {
builder.append(", '" + metaCode + "'");
}
}
builder.append(")");
你能想到更好的解决方案吗?
最佳答案
您可以使用来自 StringUtils 的 join
, 这会让最后一个逗号消失,为您想要的结果提供一个不错的结果。
来自文档:
Joins the elements of the provided array into a single String containing the provided list of elements.
No delimiter is added before or after the list. A null separator is the same as an empty String (""). Null objects or empty strings within the array are represented by empty strings.
StringUtils.join(null, *) = null
StringUtils.join([], *) = ""
StringUtils.join([null], *) = ""
StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
StringUtils.join(["a", "b", "c"], null) = "abc"
StringUtils.join(["a", "b", "c"], "") = "abc"
StringUtils.join([null, "", "a"], ',') = ",,a"
您可以使用相同的方法:
builder.append("TABLE.METACODES in ('");
boolean isFirst = true;
StringUtils.join(cto.getEntityMetaCodes(),"','");
builder.append("')");
当集合为空时需要注意,因为使用这种方法结果将是有效的 sql:TABLE.METACODES in ('')
而您的代码将是无效的:TABLE.METACODES in ()
关于java - 在字符串之间添加 n-1 个逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11518311/