package util;

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

public class StringJoin {
   public static boolean isEmpty(CharSequence cs) {
      return cs == null || cs.length() == 0;
   }

   public static boolean isNotEmpty(CharSequence cs) {
      return !isEmpty(cs);
   }

   public static String join(Iterable<?> iterable, String separator) {
      return iterable == null ? null : join(iterable.iterator(), separator);
   }

   public static String join(Iterator<?> iterator, String separator) {
      if (iterator == null) {
         return null;
      } else if (!iterator.hasNext()) {
         return "";
      } else {
         Object first = iterator.next();
         if (!iterator.hasNext()) {
            return toNewString(first);
         } else {
            StringBuilder buf = new StringBuilder(256);
            if (first != null) {
               buf.append(first);
            }

            while(iterator.hasNext()) {
               if (separator != null) {
                  buf.append(separator);
               }

               Object obj = iterator.next();
               if (obj != null) {
                  buf.append(obj);
               }
            }

            return buf.toString();
         }
      }
   }

   public static String toNewString(Object obj) {
      return obj == null ? "" : obj.toString();
   }

   public static <T> String join(T... elements) {
      return join(elements, null);
   }

   public static String join(Object[] array, String separator) {
      return array == null ? null : join(array, separator, 0, array.length);
   }

   public static String join(Object[] array, String separator, int startIndex, int endIndex) {
      if (array == null) {
         return null;
      } else {
         int noOfItems = endIndex - startIndex;
         if (noOfItems <= 0) {
            return "";
         } else {
            StringBuilder buf = new StringBuilder(noOfItems * 16);

            for(int i = startIndex; i < endIndex; ++i) {
               if (i > startIndex) {
                  buf.append(separator);
               }

               if (array[i] != null) {
                  buf.append(array[i]);
               }
            }

            return buf.toString();
         }
      }
   }

   public static void main(String[] args) {
      ArrayList<String> strings = new ArrayList();
      strings.add("1");
      strings.add("2");
      strings.add("3");
      strings.add("4");
      String join = join(strings, ",");
      System.out.println(join);
      System.out.println(isEmpty(""));
      String[] fields = new String[]{"columnName", "columnAlisa", "fullName", "nowName", "dataType", "schema", "table", "value", "expr"};
      String dfs = join(fields, ",");
      System.out.println(dfs);
   }
}
