How to combine two-dimensional arrays in Java

I have a situation where I need to combine two two-dimensional arrays.

Object[][] getMergedResults() { Object[][] a1 = getDataFromSource1(); Object[][] a2 = getDataFromSource2(); // I can guarantee that the second dimension of a1 and a2 are the same // as I have some control over the two getDataFromSourceX() methods // concat the two arrays List<Object[]> result = new ArrayList<Object[]>(); for(Object[] entry: a1) { result.add(entry); } for(Object[] entry: a2) { result.add(entry); } Object[][] resultType = {}; return result.toArray(resultType); } 

I reviewed solutions for concatenating one-dimensional arrays in this post , but couldn't get it to work for my two-dimensional arrays.

So far, the solution I came up with is to iterate over both arrays and add each element to an ArrayList, and then return toArray () of this list of arrays. I am sure there should be a simpler solution, but so far have not been able to come with it.

+4
source share
3 answers

You can try

 Object[][] result = new Object[a1.length + a2.length][]; System.arraycopy(a1, 0, result, 0, a1.length); System.arraycopy(a2, 0, result, a1.length, a2.length); 
+3
source

You can use the Apache Commons library - ArrayUtils . Change only the index for the second dimension and combine all the rows.

+1
source

Here is the method I use to concatenate a 2D array. He partly uses Sergio Nakanishi's answer, but adds the ability to come together in both directions.

 /* * Define directions for array concatenation */ public static final byte ARRAY_CONCAT_HORIZ = 0, ARRAY_CONCAT_VERT = 1; /* * Concatenates 2 2D arrays */ public static Object[][] arrayConcat(Object[][] a, Object[][] b, byte concatDirection) { if(concatDirection == ARRAY_CONCAT_HORIZ && a[0].length == b[0].length) { return Arrays.stream(arrayConcat(a, b)).map(Object[].class::cast) .toArray(Object[][]::new); } else if(concatDirection == ARRAY_CONCAT_VERT && a.length == b.length) { Object[][] arr = new Object[a.length][a[0].length + b[0].length]; for(int i=0; i<a.length; i++) { arr[i] = arrayConcat(a[i], b[i]); } return arr; } else throw new RuntimeException("Attempted to concatenate arrays of incompatible sizes."); } /* * Concatenates 2 1D arrays */ public static Object[] arrayConcat(Object[] a, Object[] b) { Object[] arr = new Object[a.length + b.length]; System.arraycopy(a, 0, arr, 0, a.length); System.arraycopy(b, 0, arr, a.length, b.length); return arr; } 
0
source

All Articles