Join a List as a String

From CodeCodex

Implementations[edit]

Erlang[edit]

List = [ "Bart", "Lisa", "Marge", "Barney", "Homer", "Maggie" ].
string:join(List, ", ").

Haskell[edit]

let list = [ "Bart", "Lisa", "Marge", "Barney", "Homer", "Maggie" ]
unwords(list)

Java[edit]

 import java.util.*;

public class CollectionUtils {
  
  public static String join(List<String> list){
    Iterator<String> i = list.iterator();
    StringBuilder sb = new StringBuilder();
    for (;;) {
      sb.append(i.next());
      if (!i.hasNext()) break;
      sb.append(", ");
    }
    return sb.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(join(list));
    /*
     * output : 
     *    Bart, Lisa, Marge, Barney, Homer, Maggie
     */
  }
}

Ruby[edit]

list = [ "Bart", "Lisa", "Marge", "Barney", "Homer", "Maggie" ]
puts list.join(", ")