Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you convert a 2 dimensional array into a 1 dimensional array in Java

Tags:

java

arrays

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 help me? Thanks.

public class TESTER1 {

    /**
     * @param args
     */

    static String[][] data = new String[][] {{"Dum","Dumer","Dumbest"}};

    public static void main(String[] args) {

        convertData(data);
    }

    public static void convertData(String[][]data) {
        String[] toReturn = new String[data.length];
        for(int i = 0;i<data.length;i++) {
            for(int j = 0;j<3;j++){
                toReturn[i] = data[i][j];
            }
        }
        for(String s:toReturn) {
            System.out.println(s);
        }
    }
}

[edit]Thank you very much. Is it possible to convert each row in the String[][] into a index in a String[] for example if we convert the String[][] (above code), then when i print out array[0] it should print out dum,dummer,dumbest [edit]

like image 982
Jeel Shah Avatar asked Mar 29 '11 00:03

Jeel Shah


1 Answers

public static String[] flatten(String[][] data) {
    ArrayList<String> list = new ArrayList<String>();

    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<String> list = new ArrayList<String>();

    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]);
}
like image 52
pajton Avatar answered Nov 14 '22 22:11

pajton