join Iterable<?> to String - Java java.lang

Java examples for java.lang:String Join

Introduction

The following code shows how to join.

Demo Code

//package com.java2s;

import java.util.Iterator;

public class Main {
    public static String join(Object[] target, String separator) {

        final StringBuilder sb = new StringBuilder();
        if (target.length > 0) {
            sb.append(target[0]);/*from   ww w  .ja  v  a 2  s  . c  o  m*/
            for (int i = 1; i < target.length; i++) {
                sb.append(separator);
                sb.append(target[i]);
            }
        }
        return sb.toString();
    }

    public static String join(Iterable<?> target, String separator) {

        StringBuilder sb = new StringBuilder();
        Iterator<?> it = target.iterator();
        if (it.hasNext()) {
            sb.append(it.next());
            while (it.hasNext()) {
                sb.append(separator);
                sb.append(it.next());
            }
        }
        return sb.toString();

    }
}

Related Tutorials