I would like to know how to convert a 2 dimensional array into a 1 dimensional array. I have come up with some code but it doesn\'t exactly seem to work. Can someone please
public static String[] flatten(String[][] data) {
ArrayList list = new ArrayList();
for(int i = 0; i < data.length; i++) {
for(int j = 0; j < data[i].length; j++){
list.add(data[i][j]);
}
}
return list.toArray(new String[0]);
}
Or add whole rows at one time:
for(int i = 0; i < data.length; i++) {
list.addAll( Arrays.asList(data[i]) );
}
Edit: From comments on my answer it seems like this is what the OP wanted (i.e. converting each row of 2d array to some string representation of it):
public static String[] rowsToString(String[][] data) {
ArrayList list = new ArrayList();
for(int i = 0; i < data.length; i++) {
String row = Arrays.toString(data[i]);
list.add( row.substring(1, row.length()-1) );
}
return list.toArray(new String[0]);
}