Returns a token string from a collection. - Android java.util

Android examples for java.util:Collection

Description

Returns a token string from a collection.

Demo Code


//package com.book2s;

import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "book2s.com");
        String delimiter = "book2s.com";
        String delimiterReplacement = "book2s.com";
        System.out.println(toTokenString(collection, delimiter,
                delimiterReplacement));/*  w  w w  .  ja  va  2  s  .c  o  m*/
    }

    private static final String EMPTY_STRING = "";

    /**
     * Returns a token string from a collection. Uses {@code Object#toString()}
     * to get the collection elements strings.
     *
     * @param collection           collection
     * @param delimiter            delimiter
     * @param delimiterReplacement replacement for all delimiters contained in
     *                             a collection's element
     * @return                     token string
     */
    public static String toTokenString(
            Collection<? extends Object> collection, String delimiter,
            String delimiterReplacement) {
        if (collection == null) {
            throw new NullPointerException("collection == null");
        }

        if (delimiter == null) {
            throw new NullPointerException("delimiter == null");
        }

        if (delimiterReplacement == null) {
            throw new NullPointerException("delimiterReplacement == null");
        }

        StringBuilder tokenString = new StringBuilder();
        int index = 0;

        for (Object o : collection) {
            tokenString.append(((index == 0) ? EMPTY_STRING : delimiter));
            tokenString.append(o.toString().replace(delimiter,
                    delimiterReplacement));
            index++;
        }

        return tokenString.toString();
    }
}

Related Tutorials