Skip to content
Advertisement

How to get odd or even lines from a two-dimensional array?

How to get odd or even lines from a two-dimensional array?

String myData [][] = {
        {"test1","test1","test1","test1"},
        {"test2","test2","test2","test2"},
        {"test3","test3","test3","test3"},
        {"test4","test4","test4","test4"},
        {"test5","test5","test5","test5"},
        {"test6","test6","test6","test6"}
    };

And write them into 1 or 2 new arrays. Need to get:

String oddLines [][] = { 
    {"test1","test1","test1","test1"},
    {"test3","test3","test3","test3"},
    {"test5","test5","test5","test5"}};

String evenLines [][] = { 
    {"test2","test2","test2","test2"},
    {"test4","test4","test4","test4"},
    {"test6","test6","test6","test6"}};

myData Array size unknown, maybe <5 , <6

Advertisement

Answer

You can use math. You know that there will be half even and half odd. You can use that and a loop to copy the values from the original array to the new arrays. Something like,

String[][] evenLines = new String[myData.length / 2][];
String[][] oddLines = new String[myData.length - evenLines.length][];
for (int i = 0; i < myData.length; i++) {
    oddLines[i / 2] = myData[i];
    if (i + 1 < myData.length) {
        evenLines[i / 2] = myData[i + 1];
        i++;
    }
}
System.out.printf("oddLines: %s%n", Arrays.deepToString(oddLines));
System.out.printf("evenLines: %s%n", Arrays.deepToString(evenLines));

Outputs

oddLines: [[test1, test1, test1, test1], [test3, test3, test3, test3], [test5, test5, test5, test5]]
evenLines: [[test2, test2, test2, test2], [test4, test4, test4, test4], [test6, test6, test6, test6]]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement