Method of converting java String to Double two dimensional array
- 2020-05-10 18:09:01
- OfStack
WHY
A friend asks a question in a group. The prototype of the question is as follows:
String str = "{{10.14, 11.24, 44.55, 41.01},{12.10, 14.21, 52.14, 50.44},{14.44, 16.12, 45.42, 47.55}}";
into double[][]{
{10.14, 11.24, 44.55, 41.01},
{12.10, 14.21, 52.14, 50.44},
{14.44, 16.12, 45.42, 47.55}
}
That is, you convert an String to an double 2-dimensional array.
HOW
At first glance, it seems very simple to implement 1, according to the convention to first paste the code:
String str = "{{10.14, 11.24, 44.55, 41.01},{12.10, 14.21, 52.14, 50.44},{14.44, 16.12, 45.42, 47.55}}";
str = str.replace("{", "[").replace("}", "]");
String[][] arr = JSON.parseObject(str, String[][].class);
Double[][] ds = new Double[arr.length][arr[0].length];
for(int j=0;j<arr.length;j++){
for(int i=0;i<arr[0].length;i++){
ds[j][i] = Double.valueOf(arr[j][i]);
}
}
There are a couple of things to notice about this
1. Replace the curly braces with the brackets,
2. Using the JSON conversion, first convert to a 2-dimensional array of String
3. Then convert the values in the array to Double
4. The JSON package I use is fastjson
import com.alibaba.fastjson.JSON;