說我有一個字符串隨機放置在其他字符周圍的空格和逗號。從逗號分隔的字符串創建ArrayList沒有空格
String str = "item1 , it em 2, ite m 3"
我如何與項目的ArrayList像
[item1, item2, item3]
說我有一個字符串隨機放置在其他字符周圍的空格和逗號。從逗號分隔的字符串創建ArrayList沒有空格
String str = "item1 , it em 2, ite m 3"
我如何與項目的ArrayList像
[item1, item2, item3]
使用以下命令:
String str = "item1 , it em 2, ite m 3"
String[] splitArray = str.split(",");
ArrayList<String> list = new ArrayList<String>();
for (String s:splitArray)
{
list.add(s.replace(" ", ""));
}
只是爲了好玩:-)
import org.apache.commons.lang3.StringUtils;
String inputString = "item1 , it em 2, ite m 3";
List<String> stringList = Arrays.stream(StringUtils.deleteWhitespace(inputString).split(",")).collect(Collectors.toList());
這裏的另一種解決方案
//Given string
String str = "item1 , it em 2, ite m 3";
//Match one or more occurrence of space in the string and replace by empty
String pattern = "\\s+";
str = str.replaceAll(pattern, "");
//Split by , and convert to ArrayList
List<String> items = Arrays.asList(str.split(","));
for(String temp: items)
System.out.println(temp);
使用Java 8的parallelSetAll
String str = "item1 , it em 2, ite m 3";
String[] stringlist = str.split(",");
Arrays.parallelSetAll(stringlist, (i) -> stringlist[i].replaceAll(" ",""));