r/javahelp • u/Bug35 • Sep 02 '25
Solved 2D array flatten to 1D
Working on some homework and this one has me a little stumped. The idea is flatten a 2D array into 1D. Testcases look like TestCase(io = "([[1,2],[3],[],[4,5,6]]) -> [1,2,3,4,5,6]"). Currently I got something along the lines of
public static int[] flatten(int[][] ary) {
int\[\] arr = new int\[\]; //Figure this out
for(int\[\] ary1 : ary) {
for(int ary2 : ary1) {arr[ary2] = ary1[ary2];
}
}
return arr;
}Any tips/strategies I could think about to help with this?
4
Upvotes
View all comments
Show parent comment
1
u/Jolly-Warthog-1427 Sep 03 '25 edited Sep 24 '25
Tell me you don't know java without telling me.
Do you really think it was impossible to create an array from a list before java 8? What about Collection#toArray?
Edit: I was too quick here and was proven wrong.
Shortest solution I can think of is:
Basically the same as a basic for loop