1. 程式人生 > >Java List轉換為字符串的幾種方法

Java List轉換為字符串的幾種方法

pty png .com detail log sem sep static size

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轉換為字符串的幾種方法

Java List轉換為字符串的幾種方法