字符串 s = "0,0,0,0,0\n,0,0,0,0,0\n,0,0,0,0,0\n,0,0,0,0 ,0\n,0,0,0,0,0\n";
这就是我期望的结果。
00000 00000 00000 00000 00000
I need to make 2D arraylist.
I tried this:
String temp = s;
String[] tempRow = temp.split("\n");
ArrayList<ArrayList<String>> mat = new ArrayList<ArrayList<String>>();
for(int i = 0; i<tempRow.length; i++){
ArrayList<String> row = new ArrayList<String>(tempRow.length);
String[] a = s.split(",");
String[] b = a[i].split("\n");
for (int j = 0; j<tempRow.length;j++){
row.add(a[i]);
}
mat.add(row);
}
但是拆分“,”不起作用。
有没有正确的方法来制作二维数组列表?
最佳答案
您当前的方法有点偏离,相反,它应该如下所示:
List<List<String>> accumulator = new ArrayList<>();
for (String str : s.split("\n")) {
List<String> tempList = new ArrayList<>();
for (String e : str.split(","))
if (!e.isEmpty())
tempList.add(e);
accumulator.add(tempList);
}
或者使用流 API,可以使用:
List<List<String>> result = Pattern.compile("\n")
.splitAsStream(s)
.map(e -> Arrays.stream(e.split(","))
.filter(a -> !a.isEmpty()).collect(toList()))
.collect(toList());
后一个解决方案需要以下导入:
import static java.util.stream.Collectors.*;
关于java - 如何在java中使用split创建二维数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50570622/