用分隔符连接字符串值以处理空字符串和空字符串? [英] Concatenate string values with delimiter handling null and empty strings?
问题描述
在Java 8中,我有一些String
值,并且我想以逗号分隔的有效值列表结尾.如果String
为 null或为空,我想忽略它.我知道这似乎很常见,很像
In Java 8 I have some number of String
values and I want to end up with a comma delimited list of valid values. If a String
is null or empty I want to ignore it. I know this seems common and is a lot like this old question; however, that discussion does not address nulls AND spaces (I also don't like the accepted answer).
我看过Java 8 StringJoiner
,Commons StringUtils
(join
)和可信赖的Guava(Joiner
),但似乎没有一个完整的解决方案.愿景:
I've looked at Java 8 StringJoiner
, Commons StringUtils
(join
) and trusty Guava (Joiner
) but none seems like a full solution. The vision:
where: val1 = "a", val2 = null, val3 = "", val4 = "b"
String niceString = StringJoiner.use(",").ignoreBlanks().ignoreNulls()
.add(val1).add(val2).add(val3).add(val4).toString();
...将导致niceString
= a,b
...would result in niceString
= a,b
有没有一种好方法(不涉及for循环,将字符串加载到列表中和/或使用regex替换来删除不良条目)?
Isn't there a nice way to do this (that doesn't involve for loops, loading strings into a list, and/or regex replaces to remove bad entries)?
推荐答案
String joined =
Stream.of(val1, val2, val3, val4)
.filter(s -> s != null && !s.isEmpty())
.collect(Collectors.joining(","));
这篇关于用分隔符连接字符串值以处理空字符串和空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!