converting a Collection to a String. - Java java.util

Java examples for java.util:Collection Join

Description

converting a Collection to a String.

Demo Code

/*******************************************************************************
 * Copyright (c) 2004, 2007 Boeing.//from   w  w w.  j  a v a2 s .co  m
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
//package com.java2s;
import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

public class Main {
    public static void main(String[] argv) {
        String separator = "java2s.com";
        Object objects = "java2s.com";
        System.out.println(toString(separator, objects));
    }

    /**
     * An flexible alternative for converting a Collection to a String.
     * 
     * @param c The Collection to convert to a String
     * @param start The String to place at the beginning of the returned String
     * @param separator The String to place in between elements of the Collection c.
     * @param end The String to place at the end of the returned String
     * @return A String which starts with 'start', followed by the elements in the Collection c separated by 'separator',
     * ending with 'end'.
     */
    @SuppressWarnings("rawtypes")
    public static String toString(Collection c, String start,
            String separator, String end) {
        Iterator i = c.iterator();
        StringBuilder myString = new StringBuilder();

        if (start != null) {
            myString.append(start);
        }

        boolean first = true;
        while (i.hasNext()) {
            if (!first) {
                myString.append(separator);
            }
            myString.append(i.next().toString());
            first = false;
        }

        if (end != null) {
            myString.append(end);
        }

        return myString.toString();
    }

    public static String toString(String separator, Object... objects) {
        Collection<Object> objectsCol = new ArrayList<Object>(
                objects.length);
        for (Object obj : objects) {
            objectsCol.add(obj);
        }
        return toString(objectsCol, null, separator, null);
    }

    @SuppressWarnings("rawtypes")
    public static String toString(String separator, Collection c) {
        return toString(c, null, separator, null);
    }
}

Related Tutorials