我有一个包含数组列表的List,我想将它转换为多维数组:
/*
The logs looks something like this
[Name: Foo, From: Somewhere, To: Somewhere]
[Name: Foo1, From: Somewhere1, To: Somewhere1]
[Name: Foo2, From: Somewhere2, To: Somewhere2]
...
*/
public static void main(String[] args) {
List<ArrayList<String>> items = new ArrayList<>();
for (String logs : Reader.read(App.purchaseLog, true) /* helper method */) {
String[] singleLog = convert(logs); /* helper method */
items.add(new ArrayList<String>());
for (String data : singleLog) {
String removeBrackets = data.replaceAll("\\[", "").replaceAll("\\]", "");
String[] splitSingleLog = convert(removeBrackets.split(","));
for (String element : splitSingleLog) {
String trimmedData = element.trim();
items.get(0).add(trimmedData.substring(trimmedData.indexOf(':') + 2, trimmedData.length()));
}
}
}
// But then how can i convert it to normal 2 dimensional array?
// i am expecting it to be like this
String[][] data = {
{"Foo", "Somewhere", "Somewhere"},
{"Foo1", "Somewhere1", "Somewhere1"},
{"Foo2", "Somewhere2", "Somewhere2"}
};
}
public static String[] convert(String... array) {
return array;
}
如何循环每个ArrayList以将其更改为普通数组? 我看到几个关于将ArrayList转换为数组的例子,但它主要是一维数组(Convert ArrayList<String> to String[] array)
答案 0 :(得分:1)
您似乎无法理解多暗数组如何在Java中运行。它们不是真正的矩阵。数组数组...表示:1-dim数组,用于保存另一个1-dim数组。
只需将List<Whatever>
转换为Whatever[]
;然后你可以去做类似的事情:
Whatever[][] twodim = { row1, row2 };
或动态:
Whatever[][] twodim = new Whatever[numberOfRows][];
twodim[0] = row1;
twodim[1] = row2;
...
因此,将List<List<String>>
转换为双暗阵列就像:
List<List<String>> theStrings ... coming from somewhere
String[][] stringsAsArray = new String[theStrings.length][];
for (int i=0; i<theStrings.length;i++) {
List<String> aList = theStrings.get(i);
stringsAsArray[i] = aList.toArray(new String[aList.size()]);
}
但是:你为什么要那样做?正如你自己看到的那样:那些多暗的阵列很复杂;与List相比非常不灵活。并查看您的数据:您的问题实际上是您不使用特定类型。
换句话说:如果你的概念上有价值观,就像某些&#34; item&#34 ;; heck:然后创建一个Item类,它可以保存属于一起的值。因此,不是处理List<List<String>>
,而是处理List<Item>
而不是!
这就是你应该如何处理你的问题:退一步;并创建一个有用的面向对象模型的数据。从本质上讲,你不应该问&#34;我如何创建多维模式的字符串和东西&#34;,但是&#34;我如何完全避免&#34;?!
答案 1 :(得分:1)
您需要两个步骤,首先将List<List<X>>
转换为List<X[]>
,然后转换为X[][]
。类似的东西:
List<List<X>> listOfList = ...;
List<X[]> listOfArray a = new ArrayList<X[]>();
for (List<X> listOfXx : listOfList) listOfArray.add(listOfX.toArray(new X[0])); // fill with arrays (from inner lists)
X[][] arrayOfArray = listOfArray.toArray(new X[0][0]);