Take the 2-minute tour ×

Let's say I have a 2D array:

int[][] a = new int[4][3];

populated such that:

1 2 3
4 5 6
7 8 9
2 5 7

Is there any shortcut method in java to extract lets say column 1 as single array:

array1 = {1 4 7 2};

Currently what I am doing is traversing through the whole 2D matrix and with if condition (if j==0), I traverse over the rows and add values to 1D array.
Just wondering if there is any standard method offered in java for such tasks.

share|improve this question
Why are you traversing the whole matrix? Why not simply: for (i = 0; i < 4; i++) { b[i] = a[i][0]; }? –  Oliver Charlesworth Jul 10 '11 at 17:27
that is because i need to extract all the columns as separate arrays. and problem is the matrix is so big, so i want to know if there is some simpler method available. –  Johnydep Jul 10 '11 at 17:29
Then please update your question to explain what you're really trying to do... –  Oliver Charlesworth Jul 10 '11 at 17:31

4 Answers 4

up vote 1 down vote accepted

No there is no shortcut to doing this. You have to loop over the arrays, switching the x & y indices.

share|improve this answer
Of course, if it's a recurring pattern in your code, you should write a helper method to do it for you. Or consider whether the fact that you're continually transposing matrices means that your design is broken! –  Oliver Charlesworth Jul 10 '11 at 17:36
actually i have to calculate cosineSimilarity which requires traversing over the transposed columns and it is recursive calculation over a huge matrix of the size [2500]x[3000]. The only idea i can think of is to integrated the calculation inside the matrix for now. –  Johnydep Jul 10 '11 at 17:48

There is no such build-in method. You have to write a simple loop.

share|improve this answer

You might want to consider use of a matrix library. But this is pretty simple stuff - if this is all you need, you can probably write it quicker than you can get up to speed on a library.

share|improve this answer

Actually there is a short way of doing this:

int[] array1 = a[0];
share|improve this answer
1. This is not actually copying the array, but only slicing a reference. 2. It is referencing rows, not columns. –  Jens Erat Aug 13 '13 at 18:33
Yes you are right! Sorry. –  Jeremy Aug 14 '13 at 20:22

Your Answer


