Java 常用功能代碼片段(空格分割,lis和數組之間的相互轉換)

1、以空格方式分割字符串

str = "Hello I come from china";
String[] splited = str.split("\\s+");

2、字符串數組轉換爲List:

實現方式一:使用Stream中的Collector收集器

        String[] arrays = new String[]{"a", "b", "c"};
        List<String> listStrings = Stream.of(arrays).collector(Collectors.toList());

實現方式二:使用java.util.Arrays工具類中的asList()方法

        String[] arrays = new String[]{"a", "b", "c"};
        List<String> listStrings = Arrays.asList(arrays);

3、List 轉換爲數組

實現方式一: 使用Stream 方式

String[] ss = listStrings.stream().toArray(String[]::new);

實現方式二:使用List中的toArray()方法

String[] sss = listStrings.toArray(new String[listStrings.size()]);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章