Join a List as a StringTag(s): Language


import java.util.AbstractCollection;
import java.util.Iterator;
import java.util.ArrayList;

public class CollectionUtils {

  private CollectionUtils() {}

  public static String join (AbstractCollection<String> s) {
    return CollectionUtils.join(s, "");
  }

  public static String join
  (AbstractCollection<String> s, String delimiter)
  {
    if (s == null || s.isEmpty()) return "";
    Iterator<String> iter = s.iterator();
    StringBuilder builder = new StringBuilder(iter.next());
    while( iter.hasNext() ) {
      builder.append(delimiter).append(iter.next());
    }
    return builder.toString();
  }

  public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>();
    list.add("Bart");
    list.add("Lisa");
    list.add("Marge");
    list.add("Barney");
    list.add("Homer");
    list.add("Maggie");
    System.out.println(CollectionUtils.join(list));
    // output : BartLisaMargeBarneyHomerMaggie
    System.out.println(CollectionUtils.join(list,","));
    // output : Bart,Lisa,Marge,Barney,Homer,Maggie
  }
}

blog comments powered by Disqus