Java List 转 String

JAVA中List转换String,String转换List,Map转换String,String转换Map之间的转换工具类(调优)
https://www.cnblogs.com/cn-wxw/p/6684280.html
https://blog.csdn.net/yywusuoweile/article/details/50315377
https://blog.csdn.net/benjaminlee1/article/details/72860845

 

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<String> mList = new ArrayList<>();
        mList.add("s1");
        mList.add("s2");
        mList.add("s3");
        // // method1: In Java 8 ~ String.join(..)
        // String mListStr = String.join(",", mList);
        // String mListStr = listToString(mList);
        String mListStr = listToString2(mList);
        System.out.println("mListStr = " + mListStr);
    }

    /**
    * for all jdk version
    * @param mList
    * @return
    */
    public static String listToString(List<String> mList) {
        String convertedListStr = "";
        if (null != mList && mList.size() > 0) {
            String[] mListArray = mList.toArray(new String[mList.size()]);
            for (int i = 0; i < mListArray.length; i++) {
            if (i < mListArray.length - 1) {
                convertedListStr += mListArray[i] + ",";
            } else {
                convertedListStr += mListArray[i];
            }
            }
            return convertedListStr;
        } else return "List is null!!!";
    }

    /**
    * for jdk <= java 7
    * @param mList
    * @return
    */
    // 采用Stringbuilder.append()的方式追加
    public static String listToString2(List<String> mList) {
        final String SEPARATOR = ",";
        // mList = Arrays.asList("AAA", "BBB", "CCC");
        StringBuilder sb = new StringBuilder();
        String convertedListStr = "";
        if (null != mList && mList.size() > 0) {
            for (String item : mList) {
                sb.append(item);
                sb.append(SEPARATOR);
            }
            convertedListStr = sb.toString();
            convertedListStr = convertedListStr.substring(0, convertedListStr.length()
            - SEPARATOR.length());
            return convertedListStr;
        } else return "List is null!!!";
    }
}

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页