I have string represention of 2d array i like to convert it to 2d int array The method i found is cumbersome , what is the best way to do it ? This is my method :
private static int[][] convertMatrix() {
String mat = "[0, 10, 0, 5, 4],\n"
"[1, 3, 10, 2, 8],\n"
"[1, 8, 1, 6, 3],\n"
"[4, 10, 2, 3, 5],\n"
"[9, 0, 9, 1, 0]";
mat = mat.trim().replaceAll("\\s ","").replaceAll("(?:\\n|\\r)", "");;
String[] matarr = mat.split("],");
int[][] matrix = new int[5][5];
for(int i = 0;i<matarr.length-1;i ) {
String lineofnumbers = matarr[i].replace("[","");
String[] lineofnumArr = lineofnumbers.split(",");
int[] tmp = new int[lineofnumArr.length];
for(int ii = 0 ; ii < lineofnumArr.length;ii )
{
tmp[ii] = Integer.parseInt(lineofnumArr[ii]);
//tmp[ii] = ;
}
matrix[i] = tmp;
}
return matrix;
}
i have only java 1.8 support
how can i convert it to version with streams
and version without streams magic ?
CodePudding user response:
One way to do it with using the Streams API is like so:
int[][] ints = Arrays.stream(mat.split(",\n")) // split rows
.map(s -> s.substring(1, s.length() - 1)) // remove '[' and ']'
.map(s -> s.split(", *")) // split cols of row
.map(arr -> Arrays.stream(arr) // map String array to int array
.mapToInt(Integer::parseInt)
.toArray()
)
.toArray(int[][]::new);
System.out.println(Arrays.deepToString(ints));
Output:
[[0, 10, 0, 5, 4], [1, 3, 10, 2, 8], [1, 8, 1, 6, 3], [4, 10, 2, 3, 5], [9, 0, 9, 1, 0]]
If you don't want to use streams, a good way to start is to replace the Arrays.stream
calls with for loops.
CodePudding user response:
Split your input at each comma followed by a new line ,\n
and stream over the resulting array, remove [
and ]
, map to stream by spliting at comma and space \\s*,\\s*
and streaming over the resulting array, parse the elements of the stream to int and collect each sub stream to array, and finally collect the arrays to a 2d-array.
int[][] result = Arrays.stream(mat.split(",\n"))
.map(str -> str.replaceAll("\\[|\\]",""))
.map(str -> Arrays.stream(str.split("\\s*,\\s*")))
.map(arr -> arr.mapToInt(Integer::parseInt).toArray())
.toArray(int[][]::new);