Java List Join joinCommaAnd(List objs)

Here you can find the source of joinCommaAnd(List objs)

Description

Returns a comma separated list, but the last comma is an "and".

License

Open Source License

Declaration

public static <T> String joinCommaAnd(List<T> objs) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Iterator;
import java.util.List;

public class Main {
    /**//from  w  w  w  .j a  va 2s. co  m
     * Returns a comma separated list, but the last comma is an "and".
     */
    public static <T> String joinCommaAnd(List<T> objs) {
        int size = objs.size();
        if (size == 0) {
            return "";
        } else if (size == 1) {
            return objs.get(0).toString();
        } else {
            StringBuilder sb = new StringBuilder();
            Iterator<T> iter = objs.iterator();
            for (int i = 0; i < size - 2; ++i) {
                sb.append(iter.next()).append(", ");
            }
            sb.append(iter.next()).append(" and ").append(iter.next());
            assert !iter.hasNext();
            return sb.toString();
        }
    }
}

Related

  1. join(T element, List otherElements)
  2. joinAndQuote(char joinChar, char quoteChar, List strings)
  3. joinArray(List list, String separator)
  4. joinArrayString(List values)
  5. joinColumnArray(List columnArray)
  6. joinCommaSeparatedList(List list)
  7. joinDoubles(List list)
  8. joinIntegers(List integers, String token)
  9. joinLines(List lines)