10

将数据从嵌套列表转换为对象数组(可用作 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);
}

非常感谢!

4

4 回答 4

12
//defined somewhere
List<List<String>> lists = ....

String[][] array = new String[lists.size()][];
String[] blankArray = new String[0];
for(int i=0; i < lists.size(); i++) {
    array[i] = lists.get(i).toArray(blankArray);
}

我对 JTable 一无所知,但是只需几行就可以将列表列表转换为数组。

于 2008-12-16T18:02:41.563 回答
8

特别是,我JTable建议AbstractTableModel像这样子类化:

class MyTableModel extends AbstractTableModel {
    private List<List<String>> data;
    public MyTableModel(List<List<String>> data) {
        this.data = data;
    }
    @Override
    public int getRowCount() {
        return data.size();
    }
    @Override
    public int getColumnCount() {
        return data.get(0).size();
    }
    @Override
    public Object getValueAt(int row, int column) {
        return data.get(row).get(column);
    }
    // optional
    @Override
    public void setValueAt(Object aValue, int row, int column) {
        data.get(row).set(column, aValue);
    }
}

注意:这是可能的最基本的实现;为简洁起见,省略了错误检查。

使用这样的模型,您不必担心无意义的Object[][].

于 2008-12-16T16:42:43.283 回答
3

Java 11 答案。

List<List<String>> table = List.of(List.of("A", "B"), List.of("3", "4"));
String[][] finalData = table.stream()
        .map(arr -> arr.toArray(String[]::new))
        .toArray(String[][]::new);
    
System.out.println(Arrays.deepToString(finalData));

[[A, B], [3, 4]]

Collection.toArray​(IntFunction<T[]> generator)方法是 Java 11 中的新方法。

当然,您也可以在 Java 8+ 中使用流。只需使用此映射:

.map(arr -> arr.toArray(new String[0]))

(该List.of方法是在 Java 9 中引入的。)

于 2018-12-19T10:09:59.803 回答
0

要将嵌套列表转换为二维对象数组,可以使用以下代码:

public Object[][] ToObjectMatrix(List<List<String>> data) throws IllegalArgumentException {
    if(data == null) {
        throw new IllegalArgumentException("Passed data was null.");
    }

    Object[][] result = new Object[data.size()][];
     
    for(int i = 0; i < data.size(); i++) {
        result[i] = data.get(i).toArray();
    }
     
    return result;
}
于 2021-03-23T14:39:46.317 回答