Java Iterable Join join(Iterable values, String separator)

Here you can find the source of join(Iterable values, String separator)

Description

join

License

Apache License

Declaration

public static <T> String join(Iterable<T> values, String separator) 

Method Source Code

//package com.java2s;
/**//from  w  w  w  .  j a  v  a  2s .  c o  m
 * Copyright 2010 Bing Ran<bing_ran@gmail.com> 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at http://www.apache.org/licenses/LICENSE-2.0.
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */

import java.util.Arrays;
import java.util.Iterator;

public class Main {
    public static <T> String join(Iterable<T> values, String separator) {
        if (values == null) {
            return "";
        }
        Iterator<T> iter = values.iterator();
        if (!iter.hasNext()) {
            return "";
        }
        StringBuffer toReturn = new StringBuffer(stringVal(iter.next()));
        while (iter.hasNext()) {
            toReturn.append(separator).append(stringVal(iter.next()));
        }
        return toReturn.toString();
    }

    public static String join(Object[] values, String separator) {
        return (values == null) ? "" : join(Arrays.asList(values), separator);
    }

    /**
     * @author Bing Ran (bing.ran@gmail.com)
     * @param cc
     * @param separator
     * @return
     */
    public static String join(char[] cc, String separator) {
        StringBuffer sb = new StringBuffer();
        for (char c : cc) {
            sb.append(c).append(separator);
        }
        return sb.toString().substring(0, sb.length() - separator.length());
    }

    private static <T> String stringVal(T i) {
        if (i instanceof char[]) {
            return new String((char[]) i);
        } else
            return String.valueOf(i);
    }
}

Related

  1. join(Iterable coll, String separator)
  2. join(Iterable items, String delimiter)
  3. join(Iterable iterable)
  4. join(Iterable parts, String delimiter)
  5. join(Iterable sequence, String delimiter)
  6. join(Iterable values, String separator)
  7. join(Iterator iterator, String separator)
  8. join(String delimiter, Iterable strings)
  9. join(String delimiter, Iterable stringsIterable)