What's the best way to build a string of delim

2018-12-31 07:39发布

While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:

public String appendWithDelimiter( String original, String addition, String delimiter ) {
    if ( original.equals( "" ) ) {
        return addition;
    } else {
        return original + delimiter + addition;
    }
}

String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );

I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.

In Ruby, I can do something like this instead, which feels much more elegant:

parameterArray = [];
parameterArray << "elementName" if condition;
parameterArray << "anotherElementName" if anotherCondition;
parameterString = parameterArray.join(",");

But since Java lacks a join command, I couldn't figure out anything equivalent.

So, what's the best way to do this in Java?

标签: java string
30条回答
不再属于我。
2楼-- · 2018-12-31 08:16

In the case of Android, the StringUtils class from commons isn't available, so for this I used

android.text.TextUtils.join(CharSequence delimiter, Iterable tokens)

http://developer.android.com/reference/android/text/TextUtils.html

查看更多
唯独是你
3楼-- · 2018-12-31 08:16

Your approach is not too bad, but you should use a StringBuffer instead of using the + sign. The + has the big disadvantage that a new String instance is being created for each single operation. The longer your string gets, the bigger the overhead. So using a StringBuffer should be the fastest way:

public StringBuffer appendWithDelimiter( StringBuffer original, String addition, String delimiter ) {
        if ( original == null ) {
                StringBuffer buffer = new StringBuffer();
                buffer.append(addition);
                return buffer;
        } else {
                buffer.append(delimiter);
                buffer.append(addition);
                return original;
        }
}

After you have finished creating your string simply call toString() on the returned StringBuffer.

查看更多
临风纵饮
4楼-- · 2018-12-31 08:17

If you're using Eclipse Collections, you can use makeString() or appendString().

makeString() returns a String representation, similar to toString().

It has three forms

  • makeString(start, separator, end)
  • makeString(separator) defaults start and end to empty strings
  • makeString() defaults the separator to ", " (comma and space)

Code example:

MutableList<Integer> list = FastList.newListWith(1, 2, 3);
assertEquals("[1/2/3]", list.makeString("[", "/", "]"));
assertEquals("1/2/3", list.makeString("/"));
assertEquals("1, 2, 3", list.makeString());
assertEquals(list.toString(), list.makeString("[", ", ", "]"));

appendString() is similar to makeString(), but it appends to an Appendable (like StringBuilder) and is void. It has the same three forms, with an additional first argument, the Appendable.

MutableList<Integer> list = FastList.newListWith(1, 2, 3);
Appendable appendable = new StringBuilder();
list.appendString(appendable, "[", "/", "]");
assertEquals("[1/2/3]", appendable.toString());

If you can't convert your collection to an Eclipse Collections type, just adapt it with the relevant adapter.

List<Object> list = ...;
ListAdapter.adapt(list).makeString(",");

Note: I am a committer for Eclipse collections.

查看更多
谁念西风独自凉
5楼-- · 2018-12-31 08:17

You're making this a little more complicated than it has to be. Let's start with the end of your example:

String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );

With the small change of using a StringBuilder instead of a String, this becomes:

StringBuilder parameterString = new StringBuilder();
if (condition) parameterString.append("elementName").append(",");
if (anotherCondition) parameterString.append("anotherElementName").append(",");
...

When you're done (I assume you have to check a few other conditions as well), just make sure you remove the tailing comma with a command like this:

if (parameterString.length() > 0) 
    parameterString.deleteCharAt(parameterString.length() - 1);

And finally, get the string you want with

parameterString.toString();

You could also replace the "," in the second call to append with a generic delimiter string that can be set to anything. If you have a list of things you know you need to append (non-conditionally), you could put this code inside a method that takes a list of strings.

查看更多
旧人旧事旧时光
6楼-- · 2018-12-31 08:18

Apache commons StringUtils class has a join method.

查看更多
看风景的人
7楼-- · 2018-12-31 08:18

So a couple of things you might do to get the feel that it seems like you're looking for:

1) Extend List class - and add the join method to it. The join method would simply do the work of concatenating and adding the delimiter (which could be a param to the join method)

2) It looks like Java 7 is going to be adding extension methods to java - which allows you just to attach a specific method on to a class: so you could write that join method and add it as an extension method to List or even to Collection.

Solution 1 is probably the only realistic one, now, though since Java 7 isn't out yet :) But it should work just fine.

To use both of these, you'd just add all your items to the List or Collection as usual, and then call the new custom method to 'join' them.

查看更多
登录 后发表回答