Java nested list to array conversion - java

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!

//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.)

To convert a nested list to a two-dimensional object-array, you can use this code:
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;
}

Related

Method in Java for creating an array with arbitrary number of dimensions

Is it possible in Java to create a method that return an array with the number of dimensions passed by parameter?
Here is the code I have so far:
public static Object buildMultiDimensionalArray(int numDimensions) {
if (numDimensions==1) {
return new int[1];
}
if (numDimensions==2) {
return new int[2][2];
}
if (numDimensions==3) {
return new int[3][3][3];
}
if (numDimensions==4) {
return new int[4][4][4][4];
}
if (numDimensions==5) {
return new int[5][5][5][5][5];
}
if (numDimensions==6) {
return new int[6][6][6][6][6][6];
}
// and so on...
return null;
}
But this works only for dimensions up to 6.
Is it possible to make this method work for any number of dimensions?
import java.lang.reflect.*;
import java.util.*;
public static Object nArray(int n) {
int[]dim = new int [n];
Arrays.fill(dim, n);
return Array.newInstance(int.class,dim);
}
Such many-dimension array is rarely seen in code. Maybe you could try one dimension array with the tuple(d1, d2 ...) mapped to the 1-d array index, the same power. for example, to visit the 2-nd row and 3-rd column of a[6][8], mapped to (2 * 8 + 3) 1-d array a[48]
You could return a single-dimension array with an explicit capacity and parse it as if it were a multidimensional array.
#SuppressWarnings("unchecked")
public static <T> T[] buildMultiDimensionalArray(int dimensions, Class<T> clazz) {
return (T[]) Array.newInstance(clazz, dimensions * dimensions);
}
class nArray {
int[] dims;
int[] mults;
int[] vals;
nArray(int ... d) {
int sum = 1;
int len = d.length;
dims = new int[len];
mults = new int[len];
for (int i=len-1; i>=0; i--) {
dims[i]=d[i];
mults[i] = sum;
sum*=d[i];
}
vals = new int[sum];
}
void set(int v, int ... d) {
int index = 0;
for (int i=0; i<d.length; i++) {
//if(d[i]>=dim[i]){throw new IndexOutOfBoundsException(); / NullPointerException } ???
index+=d[i]*mults[i];
}
vals[index] = v;
}
int get(int ... d) {
int index = 0;
for (int i=0; i<d.length; i++) {
// throw exception ?
index+=d[i]*mults[i];
}
return vals[index];
}
}
https://pastebin.com/k0hqcu5Y

Problems with calling a member of array of strings

With the help of the community i managed to get this problem solved: How to convert String to the name of the Array?
But now i get 'nullPointerExceptions'. Here is the code i use:
public class IroncladsAdder
{
public static String weaponId = null;
public static String ship = null;
public static String wing = null;
//map code
private static Map<String, List<Integer>> arrays = new HashMap<String, List<Integer>>();
public void Holder(String... names) {
for (String name : names) {
arrays.put(name, new ArrayList<Integer>());
}
}
//adds weapons to fleets and stations
public static void AddWeapons(CargoAPI cargo, String fac, int count, int type) {
String arrayName = null;
int quantity = (int) (Math.random()*5f + count/2) + 1;
if (count == 1) {quantity = 1;}
if (type == 0) {arrayName = fac+"_mil_weps";}
else if (type == 1) {arrayName = fac+"_civ_weps";}
else {arrayName = fac+"_tech_weps";}
List<Integer> array = arrays.get(arrayName);
for (int j = 0; j <= count; j++)
{
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
cargo.addWeapons(weaponId, quantity);
}
}
Here is an example of the array:
//high-tech UIN weapons
private static String [] uin_tech_weps =
{
"med-en-uin-partpulse",
"lrg-en-uin-partacc",
"med-bal-uin-driver",
"lrg-bal-uin-terminator",
"lrg-bal-uin-hvydriver",
"lrg-bal-uin-shotgundriver",
"lrg-en-uin-empbeam",
};
Error indicates that something is wrong with this construction:
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
NOTE: i`m using Intellij IDEA and Java 6. Application most of the time has advices/fixes for some errors and in this case shows that everything is ok.
What i need is to get a String out of the specific array (that is using a code-generated name) and assign it to 'weaponId'.
When your application start the map with the arrays is empty, then when you try to get the array with name X you get back a null value.
First solution: at startup/construction time fill the map with empty arrays/List for all the arrays names.
Second solution: use this method in order to obtain the array.
protected List<Integer> getArray(String arrayName) {
List<Integer> array = map.get(arrayName);
if (array == null) {
array = new ArrayList<Integer>();
map.put(arrayName, array);
}
return array;
}
P.s.
You can change this code:
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
into
weaponId = valueOf(array.get((int) (Math.random() * array.size())));
Ok. Now there is a different error - 'java.lang.IndexOutOfBoundsException: Index: 0, Size: 0'
Made the code look like this:
private static Map <String, List<Integer>> arrays = new HashMap<String, List<Integer>>();
public static List<Integer> getArray(String arrayName) {
List<Integer> array = arrays.get(arrayName);
if (array == null) {
array = new ArrayList<Integer>();
arrays.put("rsf_civ_weps", array);
arrays.put("rsf_mil_weps", array);
arrays.put("rsf_tech_weps", array);
arrays.put("isa_civ_weps", array);
arrays.put("isa_mil_weps", array);
arrays.put("isa_tech_weps", array);
arrays.put("uin_mil_weps", array);
arrays.put("uin_tech_weps", array);
arrays.put("uin_civ_weps", array);
arrays.put("xle_civ_weps", array);
arrays.put("xle_mil_weps", array);
arrays.put("xle_tech_weps", array);
}
return array;
}
This is how i now call the array and weaponId:
List<Integer> array = arrays.get(arrayName);
for (int j = 0; j <= count; j++)
{
weaponId = valueOf(array.get((int) (Math.random() * array.size())));
cargo.addWeapons(weaponId, quantity);
}
What`s wrong?

How to pass an 2D array to jtable in Netbeans

It is my first time I create a jtable,I want to display a jtable of int from another class.So I call the method getTable and assign it to the jtable,is it right?
jTable1 = new javax.swing.JTable();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new int[][] = TableAdapter.getTableC()
));
jScrollPane1.setViewportView(jTable1);
It keeps saying arraydimension missing, then I call the method getDimension() and I inserted it in various ways
new int[getDimension()][] = TableAdapter.getTableC()
or
new int[getDimension()][new int[getDimension()][] = TableAdapter.getTableC()
Thanks in adavance, and I am using Netbeans.
I get the an animal table which has two types of animals and from this I interpret to integer code which is stored in a new table(tableC) just to make it easier
package tigers.bunnies;
public class TableAdapter {
static public int tableC[][];//=new int[3][3];
static private int dimension;
public void Table(){
Animal tableT[][];
tableT = table.getTable();
dimension=tableT.length;
//int tableC[][];
tableC = new int[dimension][dimension];
for(int i=0;i<dimension;i++){
for(int j=0;j<dimension;j++){
if(tableT[i][j]==null){
tableC[i][j]=0000;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0001;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0002;
}
}
}
}
public static int[][] getTableC() {
return tableC;
}
public static int getDimension() {
return dimension;
}
}
also when I use
jTable1.setModel(new javax.swing.table.DefaultTableModel(
TableAdapter.getTableC()
));
it has these errors:
(C:\Users\user\Desktop\error.png)
Your getTableC method is static but your Table method, which initializes the array, is not, resulting in returning an uninitialized array. make Table method static or remove static keyword from getTableC, tableC and dimmension and make Table method a constructor.
package tigers.bunnies;
public class TableAdapter {
public int tableC[][];//=new int[3][3];
private int dimension;
public TableAdapter(){
Animal tableT[][];
tableT = table.getTable();
dimension=tableT.length;
//int tableC[][];
tableC = new int[dimension][dimension];
for(int i=0;i<dimension;i++){
for(int j=0;j<dimension;j++){
if(tableT[i][j]==null){
tableC[i][j]=0000;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0001;
}
else if(tableT[i][j] instanceof tiger){
tableC[i][j]=0002;
}
}
}
}
public int[][] getTableC() {
return tableC;
}
public int getDimension() {
return dimension;
}
Also, an int array is not an Object array. Change it to Integer before passing to JTable model:
TableAdapter ta = new TableAdapter();
int[][] temp = ta.getTableC();
Integer[][] Result = new Integer[temp.length][temp[0].length];
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++)
result[i][j] = new Integer(temp[i][j]);
}
Object[] header = {"Column1", "Column2"};
jTable1.setModel(new javax.swing.table.
DefaultTableModel(result, header)
Probably your TableAdapter.getTable() method returns an array of single dimension. Also you didn't supply the table header but I don't think it's the direct cause of the exception. You should call setModel this way:
Object[] header = {"Column1", "Column2..."};
jTable1.setModel(new javax.swing.table.
DefaultTableModel(TableAdapter.getTableC(), header)

Java, filling Object[][] array with data

I'm trying to fill an Object[][] array with data from my Object Class. However im having problems filling the array. Below is what I am trying to do to fill the Object[][] data. at the moment the returned data variable cannot be seen by the method. I have tried removing the method and filling the array where rows in declared but cannot because there is a for loop.
Am I currently filling the object[][] array correctly?
public class CustomersDialog extends javax.swing.JDialog {
private CustomerList customers = new CustomerList();
Object rows[][] = getData();
public Object[][] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Customer customer = new Customer();
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
Object [][] data = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
}
Further doing this method of creating the array outside the loop causes an 'empty statement message' by the compiler and it says it 'requires line ends ; after the .get statements':
public Object[][] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Customer customer;
Object [][] data;
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
data = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
You're not doing it properly.
In your code, you're declaring an array INSIDE for loop, which means that after the loop, the array doesn't exist anymore. That's why you can't return data - it simply does not exist.
More about scope and lifetime of variables you can read there: http://www.c4learn.com/javaprogramming/the-scope-and-lifetime-of-variables-in-java-programming-language/
What you want to do is to declare array outside the loop:
Object [][] data;
for(int i; i < size; i++) {
// Filling data array
}
return data;
Next thing is that if you want to use an array, you should initialize it first:
Object [][] data = new Object [size][3];
Then you can fill it in for loop, like this:
for(int i; i < size; i++) {
customer = customers.getCustomerAt(i);
data[i][0] = Integer.toString(customer.getCustomerID());
data[i][1] = customer.getfName();
data[i][2] = customer.getlName();
}
You have to allocate the array in two times. Once for the rows, and after once per row.
Object[][] data = new Object[size];
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
data[i] =
new Object[]{
Integer.toString(customer.getCustomerID()),
customer.getfName(),
customer.getlName()
};
}
If you really want to use a 2 dimensional Array than you must define the size of the Array first (also if it is a n dimensional Array!)
See this content to get some clarification:
http://www.leepoint.net/notes-java/data/arrays/arrays-2D.html
It seems to me like you only have one size Parameter for the Array, so I would use a normal Array instead of a 2 dimensional one.
I would do something like this:
public Object[] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Object[] result = new Object[size];
Customer customer;
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
result[i] = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
If you have to use a 2 dimensional Object Array, than you have to define the second size dimension and fill the array like this:
for(int i = 0; i < sizeDimOne; i++) {
for(int k = 0; k < sizeDimTwo; k++) {
result[i][k] = { { Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
}
Hope this is helpful.

Converting an ArrayList into a 2D Array

In Java how do you convert a ArrayList into a two dimensional array Object[][]?
From comments: I will describe you the problem with more details: an XML file includes a list of contacts (e.g. name, address...). The only way I can obtain this information is through an ArrayList, which will be given to me. As I need to store the content of this array list in a Java Swing table in an ordered manner, I was thinking to convert it into a two dimensional array of objects
I presume you are using the JTable(Object[][], Object[]) constructor.
Instead of converting an ArrayList<Contact> into an Object[][], try using the JTable(TableModel) constructor. You can write a custom class that implements the TableModel interface. Sun has already provided the AbstractTableModel class for you to extend to make your life a little easier.
public class ContactTableModel extends AbstractTableModel {
private List<Contact> contacts;
public ContactTableModel(List<Contact> contacts) {
this.contacts = contacts;
}
public int getColumnCount() {
// return however many columns you want
}
public int getRowCount() {
return contacts.size();
}
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0: return "Name";
case 1: return "Age";
case 2: return "Telephone";
// ...
}
}
public Object getValueAt(int rowIndex, int columnIndex) {
Contact contact = contacts.get(rowIndex);
switch (columnIndex) {
case 0: return contact.getName();
case 1: return contact.getAge();
case 2: return contact.getTelephone();
// ...
}
}
}
Later on...
List<Contact> contacts = ...;
TableModel tableModel = new ContactTableModel(contacts);
JTable table = new JTable(tableModel);
The simple way is to add a method to the Contact like this:
public Object[] toObjectArray() {
return new Object[] { getName(), getAddress, /* ... */ };
}
and use it like this:
ArrayList<Contact> contacts = /* ... */
Object[][] table = new Object[contacts.size()][];
for (int i = 0; i < contacts.size(); i++) {
table[i] = contacts.get(i).toObjectArray();
}
Try this:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(..);
list.add(..);
list.add(..);
list.add(..);
list.add(..);
list.add(..);
int[][] a = new int[list.size()][list.size()];
for(int i =0; i < list.size(); i++){
for(int j =0; j <list.size(); j++){
a[i][j]= list.get(j +( list.size() * i));
}
}
I managed to find "a way" to do so, knowing the number of attributes each contacts has (6). So considering an ArrayList listofContacts
int numberOfContacts = listofContacts.size()/6;
Object[][] newArrayContent = new Object[numberOfContacts][6];
for(int x = 0; x<numberOfContacts; x++){
for(int z = 0; z < 6; z++){
int y = 6 * x;
newArrayContent [x][z] = list.get(y+z);
System.out.println(newArrayContent [x][z].toString());
}
}
What you really want is to sort the ArrayList. To do that your Contacts class must implement a Comparator method.
Check the next page for an example: http://www.java-examples.com/sort-java-arraylist-descending-order-using-comparator-example
I will recommend that you parse your XML into java objects and store the object in a custom data object. This will make it easier for you to do many operations on the available data.
Here is small tutorial on how to do it.
public static String[][] convertListIntoArrayObj(List<TeamMenuSelected> possibilities) {
int numberOfColums = 2;
int numberOfRows = possibilities.size();
String[][] values = new String[numberOfRows][numberOfColums];
for(int x=0; x<possibilities.size(); x++) {
TeamMenuSelected item = possibilities.get(x);
values[x][0] = item.getTeamName();
values[x][1] = item.getTeamCuisine();
}
return values;
}
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("element_1");
arrayList.add("element_2");
arrayList.add("element_3");
arrayList.add("element_4");
int k=0;
int row = 2, col = 2;
Object[][] objArray = new Object[row][col];
for(int i = 0 ; i < row; i++) {
for(int j = 0; j < col; j++) {
objArray[i][j] = arrayList.get(k);
k++;
if(k > arrayList.size()) {
break;
}
}
}
for(int i = 0 ; i < row; i++) {
for(int j = 0; j < col; j++) {
System.out.println("Row no "+i+" col no "+j+" "+objArray[i][j] );
}
}
}

Categories

Resources