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!
List<List<String>> list = new ArrayList<>(); list. add(Arrays. asList("a", "b", "c")); list. add(Arrays.
You can use toArray() method to convert an ArrayList to an array. Since you have ArrayList within ArrayList, you will need to iterate over each element and apply this method.
You can pass each element in {} to create a set, otherwise you have to pass set() an iterable sequence, which a single integer is not. Note that the OP updates the list in place, while you produce a new list. This is a crucial differences that you need to make explicit.
//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);
}
I don't know anything about JTable, but converting a list of lists to array can be done with a few lines.
For JTable
in particular, I'd suggest subclassing AbstractTableModel
like so:
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);
}
}
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 answer.
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]]
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:
.map(arr -> arr.toArray(new String[0]))
(The List.of
method was introduced in Java 9.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With