将List集合用字符串,逗号隔开进行拼接 ,五种方法

将List集合用字符串,逗号隔开进行拼接 ,五种方法
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码
public class ArraySplicing {
 
 
    private static String[] array = {"张三", "李四", "王五", "撒娇", "九点十几分", "没事", "圣诞节"};
    private static String str;
 
    public static void main(String[] args) {
 
 
        List<String> list = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            list.add(array[i]);
        }
        /**
         *
         * 将集合用字符串,逗号隔开拼接
         * */
        //第一种方法(灵活,可以用逗号隔开,用|线隔开)
        str = StringUtils.join(list, ",");
        System.out.println("第一种方法" + str);
        //第二种方法
        str = listToString1(list);
        System.out.println("第二种方法" + str);
        //第三种方法(灵活,可以用逗号隔开,用|线隔开)
        str = listToString2(list, ',');
        System.out.println("第三种方法" + str);
        //第四种方法
        str = listToString3(list, ",");
        System.out.println("第四种方法" + str);
        Separator separator=new Separator(",");
        //第五种方法
        str = listToString4(list, separator );
        System.out.println("第五种方法"+str);
    }
    public static String listToString1(List<String> list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i) + ",");
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }
    public static String listToString2(List list, char separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)).append(separator);
        }
        return list.isEmpty() ? "" : sb.toString().substring(0, sb.toString().length() - 1);
    }
    public static String listToString3(List list, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
            if (i < list.size() - 1) {
                sb.append(separator);
            }
        }
        return sb.toString();
    }
    public static class Separator {
        private String next = "";
        private String separator;
        public Separator(String separator) {
            this.separator = separator;
        }
        public String get() {
            String result = next;
            next = separator;
            return result;
        }
    }
    public static String listToString4(List<String> list, Separator separator) {
        StringBuilder sb = new StringBuilder();
        for (String s : list) {
            if (s != null && !"".equals(s)) {
                sb.append(separator.get()).append(s);
            }
        }
        return sb.toString();
    }

 

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18466

发表评论