在java 8中使用分隔符处理空字符串和空字符串连接字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36705880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenate string values with delimiter handling null and empty strings in java 8?
提问by eze
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 emptyI 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 中,我有一些字符串值,我想以逗号分隔的有效值列表结束。如果 String 为null 或空,我想忽略它。我知道这似乎很常见,而且很像这个老问题;但是,该讨论并未解决空值和空格(我也不喜欢接受的答案)。
I've looked at Java 8 StringJoiner, commons StringUtils (join) and trusty guava (Joiner) but none seems like a full solution. The vision:
我看过 Java 8 StringJoiner、commons StringUtils (join) 和 trusty guava (Joiner) 但似乎没有一个是完整的解决方案。愿景:
where: val1="a", val2=null, val3="", val4="b"
String niceString = StringJoiner.use(",").ignoreBlanks().ignoreNulls()
.add(val1).add(val2).add(val3).add(val4).toString();
would result in niceString = "a,b"
会导致 niceString = "a,b"
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)?
难道没有一个很好的方法来做到这一点(不涉及 for 循环、将字符串加载到列表中和/或正则表达式替换以删除错误条目)?
采纳答案by Brian Goetz
String joined =
Stream.of(val1, val2, val3, val4)
.filter(s -> s != null && !s.isEmpty())
.collect(Collectors.joining(","));