一个把List转化为以","隔开的字符串的方法

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 /**
 4  * 集合操作
 5  * @author intrl
 6  * @date 2010-12-15
 7  * @version 1.0
 8  */
 9 public class Test {
10  
11     public static void main(String[] args) {
12         List list=new ArrayList();
13         list.add("aaa");
14         list.add("bbb");
15         list.add("ccc");
16         System.out.println(listToString(list));//aaa,bbb,ccc
17     }
18      
19     public static String listToString(List stringList){
20         if (stringList==null) {
21             return null;
22         }
23         StringBuilder result=new StringBuilder();
24         boolean flag=false;
25         for (String string : stringList) {
26             if (flag) {
27                 result.append(",");
28             }else {
29                 flag=true;
30             }
31             result.append(string);
32         }
33         return result.toString();
34     }
35 }

 方法二:

 1 这代码太垃圾了 
 2 为什么不 
 4 int length = arr.length ;
 5 StringBuffer buf = new StringBuffer("");
 6 if(length > 0){
 7     buf.append(arr[0]);
 8 }
 9 for(int i = 1 ; i < length ; i++){
10    buf.append(',');
11    buf.append(arr[i]);
12 }

 方法三:

 apache common包下的StringUtils的join方法:

 StringUtils.join(list, ",");

 以下其源码:

 1 public static String join(Iterator iterator, String separator) {
 2  
 3         // handle null, zero and one elements before building a buffer
 4         if (iterator == null) {
 5             return null;
 6         }
 7         if (!iterator.hasNext()) {
 8             return EMPTY;
 9         }
10         Object first = iterator.next();
11         if (!iterator.hasNext()) {
12             return ObjectUtils.toString(first);
13         }
14  
15         // two or more elements
16         StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
17         if (first != null) {
18             buf.append(first);
19         }
20  
21         while (iterator.hasNext()) {
22             if (separator != null) {
23                 buf.append(separator);
24             }
25             Object obj = iterator.next();
26             if (obj != null) {
27                 buf.append(obj);
28             }
29         }
30         return buf.toString();
31     }

 

你可能感兴趣的:(一个把List转化为以","隔开的字符串的方法)