Converts the Collection into a String . - Java java.util

Java examples for java.util:Collection Convert

Description

Converts the Collection into a String .

Demo Code

/*******************************************************************************
 * Copyright (c) 2014 Karlsruhe Institute of Technology, Germany
 *                    Technical University Darmstadt, Germany
 *                    Chalmers University of Technology, Sweden
 * 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:/*  w  w w. j a  v a2 s .  c  o m*/
 *    Technical University Darmstadt - initial API and implementation and/or initial documentation
 *******************************************************************************/
import java.util.Collection;

public class Main {
  public static void main(String[] argv) {
    Collection collection = java.util.Arrays.asList("asdf", "java2s.com");
    System.out.println(toString(collection));
  }

  /**
   * The default separator.
   */
  public static final String SEPARATOR = ", ";

  /**
   * Converts the {@link Collection} into a {@link String}.
   * 
   * @param collection
   *          The {@link Collection} to convert.
   * @return The {@link Collection} as {@link String}.
   */
  public static String toString(Collection<?> collection) {
    return toString(collection, SEPARATOR);
  }

  /**
   * Converts the {@link Collection} into a {@link String} and uses the defined
   * separator to separate elements.
   * 
   * @param collection
   *          The {@link Collection} to convert.
   * @param separator
   *          The separator between elements.
   * @return The {@link Collection} as {@link String}.
   */
  public static String toString(Collection<?> collection, String separator) {
    StringBuffer sb = new StringBuffer();
    if (collection != null) {
      boolean afterFirst = false;
      for (Object object : collection) {
        if (afterFirst) {
          if (separator != null) {
            sb.append(separator);
          }
        } else {
          afterFirst = true;
        }
        sb.append(object.toString());
      }
    }
    return sb.toString();
  }
}

Related Tutorials