Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Join in Java (See related posts)

Join a collection of objects into a String using the specified delimiter. One thing to note is that the collection can contain any object. The object's toString() method will be used to convert said object to its String representation.

    public static String join(Collection s, String delimiter) {
        StringBuffer buffer = new StringBuffer();
        Iterator iter = s.iterator();
        while (iter.hasNext()) {
            buffer.append(iter.next());
            if (iter.hasNext()) {
                buffer.append(delimiter);
            }
        }
        return buffer.toString();
    }

Comments on this post

babygirl_15 posts on Apr 06, 2006 at 19:49
hey whats up everyone write back
darkwill posts on Jan 15, 2008 at 02:54
We can make it faster by taking the 'if' out of the loop:

    public static String join(AbstractCollection s, String delimiter) {
        StringBuffer buffer = new StringBuffer();
        Iterator iter = s.iterator();
        if (iter.hasNext()) {
            buffer.append(iter.next());
            while (iter.hasNext()) {
                buffer.append(delimiter);
                buffer.append(iter.next());
            }
        }
        return buffer.toString();
    }

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts