Clone a 2D array (matrix) in Java using Stream API
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().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Arrays; public class Main { public static int[][] clone(int[][] mat) { if (mat == null) { return null; } return Arrays.stream(mat) .map(int[]::clone) // or use .map(arr -> arr.clone()) .toArray(int[][]::new); } public static void main(String[] args) { int[][] mat = new int[][] { {3, 5, 7, 9}, {2, 4, 6}, {10, 12} }; int[][] copy = clone(mat); Arrays.stream(copy).map(Arrays::toString).forEach(System.out::println); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Arrays; public class Main { public static int[][] clone(int[][] mat) { if (mat == null) { return null; } int[][] copy = Arrays.stream(mat) .map(arr -> Arrays.copyOf(arr, arr.length)) .toArray(int[][]::new); return copy; } public static void main(String[] args) { int[][] mat = new int[][] { {3, 5, 7, 9}, {2, 4, 6}, {10, 12} }; int[][] copy = clone(mat); Arrays.stream(copy).map(Arrays::toString).forEach(System.out::println); } } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)