zoukankan      html  css  js  c++  java
  • Java List转换为字符串的几种方法

    Java List转换为字符串的几种方法

    import org.apache.commons.lang3.StringUtils;
    
    import java.util.ArrayList;
    import java.util.List;
    
    // 参考:https://blog.csdn.net/vasilis_1/article/details/75499087
    public class ListToStringTest {
    
        public static String listToString1(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 listToString2(List list, char separator) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                if (i == list.size() - 1) {
                    sb.append(list.get(i));
                } else {
                    sb.append(list.get(i));
                    sb.append(separator);
                }
            }
            return sb.toString();
        }
    
        public static String listToString3(List list, char 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 String listToString4(List list, char separator) {
            return StringUtils.join(list.toArray(), separator);
        }
    
        public static void main(String[] args) {
            List<String> list = new ArrayList<String>();
            list.add("a");
            list.add("b");
            list.add("c");
            list.add("d");
            System.out.println(ListToStringTest.listToString1(list, '+'));
            System.out.println(ListToStringTest.listToString2(list, '-'));
            System.out.println(ListToStringTest.listToString3(list, '*'));
            System.out.println(ListToStringTest.listToString4(list, '/'));
        }
    
    }
    

    参考:

    参考:java List转换为字符串的几种方法

  • 相关阅读:
    FastCgi与PHPfpm之间的关系
    PHP中多线程处理
    EASYUI+MVC4通用权限管理平台前言
    常用企业建站源码
    Oracle数据库同步服务
    Jquery easyui +MVC4 管理信息系统
    《自动化技术中的进给电气传动》1.1节和1.2节读书笔记
    FTP
    Samba
    rsync
  • 原文地址:https://www.cnblogs.com/hgnulb/p/9940306.html
Copyright © 2011-2022 走看看