Java List to String listToString(List list, String separator)

Here you can find the source of listToString(List list, String separator)

Description

list To String

License

Open Source License

Declaration

public static String listToString(List<String> list, String separator) 

Method Source Code

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

import java.util.*;

public class Main {
    public static String listToString(List<String> list, String separator) {
        if (list.isEmpty()) {
            return "";
        }/*from w  w w . ja  v a 2  s.  c  o m*/

        int n = list.size();
        StringBuilder sb = new StringBuilder();
        sb.append(list.get(0));
        if (n == 1) {
            return sb.toString();
        }

        for (int i = 1; i < n; i++) {
            sb.append(separator).append(list.get(i));
        }

        return sb.toString();
    }

    public static String listToString(List<String> list) {
        if (list.isEmpty()) {
            return "";
        }

        int n = list.size();
        StringBuilder sb = new StringBuilder();
        sb.append(list.get(0));
        if (n == 1) {
            return sb.toString();
        } else if (n == 2) {
            return sb.append(" and ").append(list.get(1)).toString();
        }

        for (int i = 1; i < n - 1; i++) {
            sb.append(", ").append(list.get(i));
        }
        sb.append(" and ").append(list.get(n - 1));

        return sb.toString();
    }
}

Related

  1. listToString(List list)
  2. listToString(List list)
  3. listToString(List list, String delimiter)
  4. listToString(List list, String expr)
  5. listToString(List list, String separator)
  6. listToString(List list, String separator)
  7. listToString(List list, String split)
  8. listToString(List params, String sepator)
  9. listToString(List pListToConvert)