逗號分隔的字符串與List相互轉換

String轉List:

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class Father{
    void methodFather(){
        System.out.println("Father");
    }
}

class Son extends Father {
    void methodSon(){
        System.out.println("Son");
    }
}

public class Test {


    public static void main(String[] args){

        String str = "1,2,3,4,5,6,7,8";

        String[] strArr= str.split(",");

        //方法一
        List<String> list = Arrays.asList(strArr);

        //方法二
        List<String> list1 = new ArrayList<>();
        Collections.addAll(list1, strArr);

        //方法三遍歷加進去



    }
}
複製代碼

List轉String:

import com.sun.deploy.util.StringUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class Father{
    void methodFather(){
        System.out.println("Father");
    }
}

class Son extends Father {
    void methodSon(){
        System.out.println("Son");
    }
}

public class Test {


    public static void main(String[] args){

        List<String> list = new ArrayList<>();

        list.add("a");
        list.add("b");
        list.add("c");

        //list轉String數組
        String[] strArr = list.toArray(new String[list.size()]);

        //String數組轉爲帶分隔符的字符串
        String str1 = String.join(",", strArr);

        //list轉爲有分隔符的字符串
        String str = StringUtils.join(list, ",");

    }
}

複製代碼
相關文章
相關標籤/搜索