Java Comma Separated List implodeCommaAnd(List list, String comma, String and)

Here you can find the source of implodeCommaAnd(List list, String comma, String and)

Description

implode Comma And

License

Apache License

Declaration

public static String implodeCommaAnd(List<String> list, String comma, String and) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    public static String implodeCommaAnd(List<String> list, String comma, String and) {
        if (list.size() == 0)
            return "";
        if (list.size() == 1)
            return list.get(0);

        String lastItem = list.get(list.size() - 1);
        String nextToLastItem = list.get(list.size() - 2);
        String merge = nextToLastItem + and + lastItem;
        list.set(list.size() - 2, merge);
        list.remove(list.size() - 1);//from w  ww  .j  a  va 2s  . co m

        return implode(list, comma);
    }

    public static String implodeCommaAnd(List<String> list) {
        return implodeCommaAnd(list, ", ", " and ");
    }

    public static String implode(List<String> list, String glue) {
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i != 0) {
                ret.append(glue);
            }
            ret.append(list.get(i));
        }
        return ret.toString();
    }
}

Related

  1. getCommaSeparatedValues(List values)
  2. getListAsCommaSeparatedString(List list)
  3. getStringList(List list, boolean useComma, boolean useBrackets, String comma)
  4. getStringListFromCommaSeparatedString(String input)
  5. humanReadableCommandLineOutput(List arguments)
  6. listToComma(List list)
  7. listToCommandLine(List commands)
  8. listToCommas(List list)
  9. listToCommaSep(List strings)