Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 BSI Business Systems Integration AG.
 * 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:
 *     BSI Business Systems Integration AG - initial API and implementation
 ******************************************************************************/

import java.util.Collection;

import java.util.Iterator;

public class Main {
    /**
     * @see #format(Collection, String, boolean)
     */
    public static <T> String format(Collection<T> list, String delimiter) {
        return format(list, delimiter, false);
    }

    /**
     * @see #format(Collection, String, boolean)
     */
    public static String format(Collection<?> list) {
        return format(list, false);
    }

    /**
     * @see #format(Collection, String, boolean)
     */
    public static <T> String format(Collection<T> c, boolean quoteStrings) {
        return format(c, ", ", quoteStrings);
    }

    /**
     * To get a string representation of a collection.
     *
     * @param list
     *          input list
     * @param delimiter
     *          the separator used between elements
     * @param quoteStrings
     *          <code>true</code> to get quoted representations of all not numbers.
     * @return a string representation of the given collection.
     */
    public static <T> String format(Collection<T> list, String delimiter, boolean quoteStrings) {
        if (isEmpty(list)) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        Iterator<T> it = list.iterator();
        // first
        result.append(objectToString(it.next(), quoteStrings));
        // rest
        while (it.hasNext()) {
            result.append(delimiter);
            result.append(objectToString(it.next(), quoteStrings));
        }
        return result.toString();
    }

    public static boolean isEmpty(Collection<?> c) {
        return c == null || c.isEmpty();
    }

    private static String objectToString(Object o, boolean quoteStrings) {
        if (o == null) {
            return "null";
        }
        if (o instanceof Number) {
            return o.toString();
        }
        if (quoteStrings) {
            return "'" + o.toString().replaceAll(",", "%2C") + "'";
        } else {
            return o.toString();
        }

    }
}