Java tutorial
//package com.java2s; /************************************************************************************** * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * **************************************************************************************/ import java.io.StringWriter; import java.util.*; public class Main { public static String toString(Collection<Integer> stack, String delimiterChars) { if (stack.isEmpty()) { return ""; } if (stack.size() == 1) { return Integer.toString(stack.iterator().next()); } StringWriter writer = new StringWriter(); String delimiter = ""; for (Integer item : stack) { writer.append(delimiter); writer.append(Integer.toString(item)); delimiter = delimiterChars; } return writer.toString(); } /** * Returns a list of the elements invoking toString on non-null elements. * @param collection to render * @param <T> type * @return comma-separate list of values (no escape) */ public static <T> String toString(Collection<T> collection) { if (collection == null) { return "null"; } if (collection.isEmpty()) { return ""; } StringBuilder buf = new StringBuilder(); String delimiter = ""; for (T t : collection) { if (t == null) { continue; } buf.append(delimiter); buf.append(t); delimiter = ", "; } return buf.toString(); } }