Concatenate string values with delimiter handling null and empty strings in java 8? [duplicate]

女生的网名这么多〃 提交于 2019-12-17 22:58:05

问题


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).

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();

would result in 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)?


回答1:


String joined = 
    Stream.of(val1, val2, val3, val4)
          .filter(s -> s != null && !s.isEmpty())
          .collect(Collectors.joining(","));


来源:https://stackoverflow.com/questions/36705880/concatenate-string-values-with-delimiter-handling-null-and-empty-strings-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!