tags:

views:

4173

answers:

23

While working in a Java app, I recently was needing 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?

+9  A: 

Use an approach based on java.lang.StringBuilder! ("A mutable sequence of characters. ")

Like you mentioned, all those string concatenations are creating Strings all over. StringBuilder won't do that.

Why StringBuilder instead of StringBuffer? From the StringBuilder javadoc:

Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Stu Thompson
+1  A: 

You can use Java's StringBuilder type for this. There's also StringBuffer, but it contains extra thread safety logic that is often unnecessary.

HTH, Kent

Kent Boogaart
+1  A: 

Why not write your own join() method? It would take as parameters collection of Strings and a delimiter String. Within the method iterate over the collection and build up your result in a StringBuffer.

Dave Costa
+8  A: 

You can generalize it, but there's no join in Java, as you well say.

This might work better.

public static String join(Iterable<? extends Charsequence> s, String delimiter) {
    if (s.isEmpty()) return "";
    Iterator<String> iter = s.iterator();
    StringBuffer buffer = new StringBuffer(iter.next());
    while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
    return buffer.toString();
}
Vinko Vrsalovic
I agree with this answer but can someone edit the signature so that it accepts Collection<String> instead of AbstractCollection<String>? The rest of the code should be the same but I think AbstractCollection is an implementation detail that doesn't matter here.
Outlaw Programmer
Better still, use `Iterable<String>` and just use the fact that you can iterator over it. In your example you don't need the number of items in the collection, so this is even more general.
Jason Cohen
Or even better, use Iterable<? extends Charsequence> and then you can accept collections of StringBuilders and Strings and streams and other string-like things. :)
Jason Cohen
You want to use a `StringBuilder` instead. They are identical, except `StringBuffer` provides unnecessary thread safety. Can someone please edit it!
Casebash
This code has several errors. 1. CharSequence has a capital s. 2. s.iterator() returns a Iterator<? extends CharSequence>. 3. An Iterable doesn't have a `isEmpty()` method, use the `next()` method instead
Casebash
A: 

You can try something like this:

StringBuilder sb = new StringBuilder();
if (condition) { sb.append("elementName").append(","); }
if (anotherCondition) { sb.append("anotherElementName").append(","); }
String parameterString = sb.toString();
martinatime
This looks like it will leave a stray comma on the end of the string, which I'd hoped to avoid. (Of course, since you know it's there, you can then trim it, but that smells a bit inelegant too.)
Sean McMains
A: 
public static String join(String[] strings, char del)
{
    StringBuffer sb = new StringBuffer();
    int len = strings.length;
    boolean appended = false;
    for (int i = 0; i < len; i++)
    {
        if (appended)
        {
            sb.append(del);
        }
        sb.append(""+strings[i]);
        appended = true;
    }
    return sb.toString();
}
izb
+1  A: 

You should probably use a StringBuilder with the append method to construct your result, but otherwise this is as good of a solution as Java has to offer.

ElectricDialect
A: 

Why don't you do in Java the same thing you are doing in ruby, that is creating the delimiter separated string only after you've added all the pieces to the array?

ArrayList<String> parms = new ArrayList<String>();
if (someCondition) parms.add("someString");
if (anotherCondition) parms.add("someOtherString");
// ...
String sep = ""; StringBuffer b = new StringBuffer();
for (String p: parms) {
    b.append(sep);
    b.append(p);
    sep = "yourDelimiter";
}

You may want to move that for loop in a separate helper method, and also use StringBuilder instead of StringBuffer...

Edit: fixed the order of appends.

agnul
Yes, why would you use StringBuffer instead of StringBuilder (as you are using Java 1.5+)? You also have your appends the wrong way around.
Tom Hawtin - tackline
+23  A: 

Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby:

StringUtils.join(java.util.Collection,char)

Martin Gladdish
I am wondering - does this take into account if the String representation of an Object in the Collection contains the delimiter character itself?
GreenieMeanie
+4  A: 

You could write a little join-style utility method that works on java.util.Lists

public static String join(List<String> list, String delim) {

    StringBuilder sb = new StringBuilder();

    String loopDelim = "";

    for(String s : list) {

        sb.append(loopDelim);
        sb.append(s);            

        loopDelim = delim;
    }

    return sb.toString();
}

Then use it like so:

    List<String> list = new ArrayList<String>();

    if( condition )        list.add("elementName");
    if( anotherCondition ) list.add("anotherElementName");

    join(list, ",");
Rob Dickerson
A: 

So basically something like this:

public static String appendWithDelimiter(String original, String addition, String delimiter) {

if (original.equals("")) {
    return addition;
} else {
    StringBuilder sb = new StringBuilder(original.length() + addition.length() + delimiter.length());
        sb.append(original);
        sb.append(delimiter);
        sb.append(addition);
        return sb.toString();
    }
}
killdash10
The problem here is that he seems to be calling appendWithDelimiter() allot. The solution should instance one and only one StringBuffer and work with that single instance.
Stu Thompson
+4  A: 

Apache commons StringUtils class has a join method.

I (heart) Apache commons. Did not even know that existed...
Stu Thompson
I hate Apache commons. The reflection-based toString helper was written by idiots, for idiots.
erickson
Well don't use that bit then. Sheesh.
skaffman
A: 

Don't know if this really is any better, but at least it's using StringBuilder, which may be slightly more efficient.

Down below is a more generic approach if you can build up the list of parameters BEFORE doing any parameter delimiting.

// Answers real question
public String appendWithDelimiters(String delimiter, String original, String addition) {
 StringBuilder sb = new StringBuilder(original);
 if(sb.length()!=0) {
  sb.append(delimiter).append(addition);
 } else {
  sb.append(addition);
 }
 return sb.toString();
}


// A more generic case.
// ... means a list of indeterminate length of Strings.
public String appendWithDelimitersGeneric(String delimiter, String... strings) {
 StringBuilder sb = new StringBuilder();
 for (String string : strings) {
  if(sb.length()!=0) {
   sb.append(delimiter).append(string);
  } else {
   sb.append(string);
  }
 }

 return sb.toString();
}

public void testAppendWithDelimiters() {
 String string = appendWithDelimitersGeneric(",", "string1", "string2", "string3");
}
Mikezx6r
A: 

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.

Yaba
Using StringBuffer here will just make it slower for no good reason. Using the + operator will internally use the faster StringBuilder so he is winning nothing but thread safety he doesn't need by using StringBuffer instead.
Fredrik
Also... The statement "The + has the big disadvantage that a new String instance is being created for each single operation" is false. The compiler will generate StringBuilder.append() calls out of them.
Fredrik
+1  A: 

I would use Google Collections. There is a nice Join facility.
http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/base/Join.html

But if I wanted to write it on my own,

package util;

import java.util.ArrayList;
import java.util.Iterable;
import java.util.Collections;
import java.util.Iterator;

public class Utils {
    // accept a collection of objects, since all objects have toString()
    public static String join(String delimiter, Iterable<? extends Object> objs) {
        if (objs.isEmpty()) {
            return "";
        }
        Iterator<? extends Object> iter = objs.iterator();
        StringBuilder buffer = new StringBuilder();
        buffer.append(iter.next());
        while (iter.hasNext()) {
            buffer.append(delimiter).append(iter.next());
        }
        return buffer.toString();
    }

    // for convenience
    public static String join(String delimiter, Object... objs) {
        ArrayList<Object> list = new ArrayList<Object>();
        Collections.addAll(list, objs);
        return join(delimiter, list);
    }
}

I think it works better with an object collection, since now you don't have to convert your objects to strings before you join them.

Eric Normand
I didn't know Google had a collections class. Thanks for the link!
Sean McMains
A: 

Instead of using string concatenation, you should use StringBuilder if your code is not threaded, and StringBuffer if it is.

Kamikaze Mercenary
A: 

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.

A: 
//Note: if you have access to Java5+, 
//use StringBuilder in preference to StringBuffer.  
//All that has to be replaced is the class name.  
//StringBuffer will work in Java 1.4, though.

appendWithDelimiter( StringBuffer buffer, String addition, 
    String delimiter ) {
    if ( buffer.length() == 0) {
        buffer.append(addition);
    } else {
        buffer.append(delimiter);
        buffer.append(addition);
    }
}


StringBuffer parameterBuffer = new StringBuffer();
if ( condition ) { 
    appendWithDelimiter(parameterBuffer, "elementName", "," );
}
if ( anotherCondition ) {
    appendWithDelimiter(parameterBuffer, "anotherElementName", "," );
}

//Finally, to return a string representation, call toString() when returning.
return parameterBuffer.toString();
MetroidFan2002
A: 

With Java 5 variable args, so you don't have to stuff all your strings into a collection or array explicitly:

import junit.framework.Assert;
import org.junit.Test;

public class StringUtil
{
    public static String join(String delim, String... strings)
    {
        StringBuilder builder = new StringBuilder();

        if (strings != null)
        {
            for (String str : strings)
            {
                if (builder.length() > 0)
                {
                    builder.append(delim).append(" ");
                }
                builder.append(str);
            }
        }           
        return builder.toString();
    }
    @Test
    public void joinTest()
    {
        Assert.assertEquals("", StringUtil.join(",", null));
        Assert.assertEquals("", StringUtil.join(",", ""));
        Assert.assertEquals("", StringUtil.join(",", new String[0]));
        Assert.assertEquals("test", StringUtil.join(",", "test"));
        Assert.assertEquals("foo, bar", StringUtil.join(",", "foo", "bar"));
        Assert.assertEquals("foo, bar, x", StringUtil.join(",", "foo", "bar", "x"));
    }
}
mbaird
A: 

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.

+1  A: 

Use StringBuilder and Class Separator.

StringBuilder $ = new StringBuilder();
Separator sep = new Separator(", ");
for (String each : list) {
    $.append(sep).append(each);
}

Separator wraps a delimiter. The delimiter is returned by Separator's toString method, unless on the first call which returns the empty string!

Adrian
A: 

using Dollar is simple as typing:

String joined = $(aCollection).join(",");

NB: it works also for Array and other data types

Implementation

Internally it uses a very neat trick:

@Override
public String join(String separator) {
    Separator sep = new Separator(separator);
    StringBuilder sb = new StringBuilder();

    for (T item : iterable) {
        sb.append(sep).append(item);
    }

    return sb.toString();
}

the class Separator return the empty String only the first time that it is invoked, then it returns the separator:

class Separator {

    private final String separator;
    private boolean wasCalled;

    public Separator(String separator) {
        this.separator = separator;
        this.wasCalled = false;
    }

    @Override
    public String toString() {
        if (!wasCalled) {
            wasCalled = true;
            return "";
        } else {
            return separator;
        }
    }
}
dfa
A: 

Slight improvement [speed] of version from izb:

public static String join(String[] strings, char del)
{
    StringBuilder sb = new StringBuilder();
    int len = strings.length;

    if(len > 1) 
    {
       len -= 1;
    }else
    {
       return strings[0];
    }

    for (int i = 0; i < len; i++)
    {
       sb.append(strings[i]).append(del);
    }

    sb.append(strings[i]);

    return sb.toString();
}
java al