Java 嵌套列表到数组的转换
将数据从嵌套列表转换为对象数组(可以用作 JTable 的数据)的最有效方法是什么?
List<List> table = new ArrayList<List>();
for (DATAROW rowData : entries) {
List<String> row = new ArrayList<String>();
for (String col : rowData.getDataColumn())
row.add(col);
table.add(row);
}
// I'm doing the conversion manually now, but
// I hope that there are better ways to achieve the same
Object[][] finalData = new String[table.size()][max];
for (int i = 0; i < table.size(); i++) {
List<String> row = table.get(i);
for (int j = 0; j < row.size(); j++)
finalData[i][j] = row.get(j);
}
非常感谢!
What is the most efficient way to convert data from nested lists to an object array (which can be used i.e. as data for JTable)?
List<List> table = new ArrayList<List>();
for (DATAROW rowData : entries) {
List<String> row = new ArrayList<String>();
for (String col : rowData.getDataColumn())
row.add(col);
table.add(row);
}
// I'm doing the conversion manually now, but
// I hope that there are better ways to achieve the same
Object[][] finalData = new String[table.size()][max];
for (int i = 0; i < table.size(); i++) {
List<String> row = table.get(i);
for (int j = 0; j < row.size(); j++)
finalData[i][j] = row.get(j);
}
Many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我对 JTable 一无所知,但是只需几行即可将列表列表转换为数组。
I don't know anything about JTable, but converting a list of lists to array can be done with a few lines.
特别是对于
JTable
,我建议像这样子类化AbstractTableModel
:注意:这是最基本的实现; 为了简洁起见,省略了错误检查。
使用这样的模型,您不必担心到
Object[][]
的无意义转换。For
JTable
in particular, I'd suggest subclassingAbstractTableModel
like so:Note: this is the most basic implementation possible; error-checking is omitted for brevity.
Using a model like this, you don't have to worry about pointless conversions to
Object[][]
.Java 11 答案。
Collection.toArray (IntFunctionGenerator)
方法是 Java 11 中的新方法。当然,您也可以在Java 8+。 只需使用此映射即可:(
List.of
方法是在 Java 9 中引入的。)Java 11 answer.
The
Collection.toArray(IntFunction<T[]> generator)
method is new in Java 11.Of course you may also use a stream in Java 8+. Just use this mapping instead:
(The
List.of
method was introduced in Java 9.)要将嵌套列表转换为二维对象数组,可以使用以下代码:
To convert a nested list to a two-dimensional object-array, you can use this code: