This post will discuss how to clone a 2D array (matrix) in Java using Stream API, whose column size may or may not be fixed.

1. Using clone() method

Since Java 8, you can use the streams API to clone a 2-dimensional array in Java. The following solution uses method reference int[]::clone for cloning, which behaves the same as using the lambda expression arr -> arr.clone().

Download  Run Code

Output:

[3, 5, 7, 9]
[2, 4, 6]
[10, 12]

2. Using Arrays.copyOf() method

Another alternative is to use the Arrays.copyOf() method to create a complete copy of a single-dimensional array. We can use Stream API .map() method to clone a 2-dimensional array, as demonstrated below:

Download  Run Code

Output:

[3, 5, 7, 9]
[2, 4, 6]
[10, 12]

That’s all about cloning a 2-dimensional array (matrix) in Java using Stream API.