將list集合轉換成字符串


 今天遇到這個問題時,發現有一個工具類可以快速解決這個問題,那就是org.apache.commons.lang3包下的StringUtils工具類下的join()方法。

 StringUtils中join()方法的使用,如下示例所示:

    import java.util.ArrayList;
    import java.util.List;
    import org.apache.commons.lang3.StringUtils;
    public class Test2 {
        public static void main(String[] args) {
            List<String> list = new ArrayList<>();
            list.add("aa");
            list.add("bb");
            list.add("cc");
            // 打印集合list
            System.out.println(list);
            // 將集合轉換成字符串
            String str = StringUtils.join(list, ",");
            //打印出字符串
            System.out.println(str);
        }
    }

 

字符串也是可以轉成集合的,首先將字符串轉成數組形式。如下示例所示:

    import java.util.Arrays;
    import java.util.List;
    public class Test2 {
        public static void main(String[] args) {
          String str="aa,bb,cc";
        //用逗號將字符串分開,得到字符串數組 String[]
          String[] strs=str.split(",");
         //將字符串數組轉換成集合list
          List<String> list = Arrays.asList(strs);
          //打印出集合
          System.out.println(list);
        }

SONObject的parseArray方法作用:
該方法將字符串數據轉換成集合對象。
String dep_tree = JedisUtils.getInstance().get(CacheConstant.DEP_TREE, user.getId());
List<TreeNode> treeNodeList = JSONObject.parseArray(dep_tree, TreeNode.class);

————————————————

String數組轉換成字符串:使用 Apache Commons 組件中的 commons-lang3.jar包

String [] a={"abc","d","ef"}; String str=StringUtils.join(a,",")// 使用逗號隔開


 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM