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


     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<String> list=new ArrayList<String>();
    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<String> 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     }
  • 相关阅读:
    实测好用的awvs批量添加任务脚本
    SQL注入漏洞
    CTF-WEB-信息泄露题目总结
    Awvs+nessus docker版本
    禅道12.4.2后台管理员权限Getshell复现
    子域名工具,使用必应搜索引擎
    i春秋第二届春秋欢乐赛-Web-Hello World
    百度杯CTF比赛 九月场-WEB-题目名称:SQL
    文件上传漏洞
    CVE-2019-17625漏洞复现(Rambox 0.6.9版本存储型XSS)
  • 原文地址:https://www.cnblogs.com/DreamDrive/p/5483492.html
Copyright © 2020-2023  润新知