To convert a list to 2-dimensional array you have to traverse inside a list and assign each element to the array.
Here I write a transformer for you;
public static String[][] transformListToArray(List<List<String>> inputList) {
int rows = inputList.size();
int columns = inputList.get(0).size();
String[][] array2d = new String[rows][columns];
for( int i = 0; i < inputList.size(); i++ )
for( int j = 0; j < inputList.get(i).size(); j++ )
array2d[i][j] = inputList.get(i).get(j);
return array2d;
}
Printing is also similiar, only you have to traverse inside the array and format the output;
I also wrote this one for printing the 2-dimensional array;
public static void print2DArray( String[][] inputArray) {
for( int i = 0; i < inputArray.length; i++ ) {
for( int j = 0; j < inputArray[i].length; j++ )
System.out.printf("%s ", inputArray[i][j]);
System.out.println();
}
}
As a complete solution, you can check this out, it's working fine;
public class TestConvert2DArray {
public static List<List<String>> dataArrayList = new ArrayList<>();
public static void main(String args[]) {
try {
readFile();
// alphaSort(); we dont need it anymore
String new2dArray[][] = transformListToArray(dataArrayList);
print2DArray(new2dArray);
} catch (Exception e) {
}
}
// To be used on transforming the list to 2d-array
public static String[][] transformListToArray(List<List<String>> inputList) {
int rows = inputList.size();
int columns = inputList.get(0).size();
String[][] array2d = new String[rows][columns];
for (int i = 0; i < inputList.size(); i++)
for (int j = 0; j < inputList.get(i).size(); j++)
array2d[i][j] = inputList.get(i).get(j);
return array2d;
}
// To be used on printing the 2d-array to the console
public static void print2DArray(String[][] inputArray) {
for (int i = 0; i < inputArray.length; i++) {
for (int j = 0; j < inputArray[i].length; j++)
System.out.printf("%s ", inputArray[i][j]);
System.out.println();
}
}
// Just added an init for textFileDirectory
public static void readFile() throws Exception {
String txtFileDirectory = "D:\\try.txt"; // "D:\\try.txt"
FileReader fileRead = new FileReader(txtFileDirectory);
BufferedReader dataReader = new BufferedReader(fileRead);
String line = "";
// And you dont need and index inside the for loop
for (; line != null;) {
line = dataReader.readLine();
if (line != null)
dataArrayList.add(Arrays.asList(line.split(",")));
}
dataReader.close(); // You have to close all the reasources to prevent
// data leak
}
}
A sample input is same with the input file;
01 - What comes around, goes around
02 - Eyes wide open
03 - What comes around, goes around
04 - Eyes wide open
05 - What comes around, goes around
06 - Eyes wide open
07 - What comes around, goes around
08 - Eyes wide open
09 - What comes around, goes around
10 - Eyes wide open