Convert Collection to String With Delimiter - Java java.util

Java examples for java.util:Collection Join

Description

Convert Collection to String With Delimiter

Demo Code


//package com.java2s;

import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "java2s.com");
        String delimiter = "java2s.com";
        System.out.println(toStringWithDelimiter(collection, delimiter));
    }//from  ww  w  .  jav  a 2  s.c o  m

    public static String toStringWithDelimiter(
            final Collection<?> collection, final String delimiter) {
        if ((collection == null) || collection.isEmpty()) {
            return "";
        }

        final StringBuilder stringBuilder = new StringBuilder(
                collection.size());
        int i = 0;
        for (final Object o : collection) {
            stringBuilder.append(o);
            ++i;
            if (collection.size() != i) {
                stringBuilder.append(delimiter);
            }

        }
        return stringBuilder.toString();
    }
}

Related Tutorials