I have a simple 2d array
// Creating and Initializing 2D array
int a[][] = {{0,1},{2,3},{4,5}};
for(int i=0; i<3; i ) {
for(int j=0; j<2; j ) {
System.out.print(a[i][j] " ");
}
System.out.println();
}
works everything fine. But how can I initialize the array when the content is dynamic and coming from a variable?
String arrContent = "{{0,1},{2,3},{4,5}}"; //actually a method readContentFromFile(); will deliver the content
int a[][] = arrContent;
Is there any way to do this?
CodePudding user response:
The input stream can be parsed using String::split
and Stream API:
- get rows splitting by comma between a pair of
},{
- remove redundant curly brackets using
String::replaceAll
- for each row, split by comma, convert numbers to int
Stream::mapToInt
and get array - collect to multidimensional array with
Stream::toArray
String arrContent = "{{0,1},{2,3},{4,5}}";
int[][] arr = Arrays.stream(arrContent.split("\\}\\s*,\\s*\\{")) //1
.map(s -> s.replaceAll("[{}]", "")) //2
.map(s -> Arrays.stream(s.split("\\s*,\\s*")) //3
.mapToInt(Integer::parseInt).toArray()
)
.toArray(int[][]::new); //4
System.out.println(Arrays.deepToString(arr));
Output
[[0, 1], [2, 3], [4, 5]]
Another approach could be to use JSON parser, however, initial input string needs to be modified to become a valid JSON array (curly brackets {}
have to be replaced with the square ones []
using simpler String::replace(char old, char rep)
):
String arrContent = "{{0,1},{2,3},{4,5}}";
ObjectMapper om = new ObjectMapper();
int[][] arr = om.readValue(
arrContent.replace('{', '[')
.replace('}', ']'),
int[][].class);
System.out.println(Arrays.deepToString(arr));
// output
[[0, 1], [2, 3], [4, 5]]
CodePudding user response:
Just wanted to provide a little bit modified solution using simple regexp just in case anybody would prefer doing it this way:
String input = "{{0,1},{2,3},{4,5}}";
Pattern pattern = Pattern.compile("\\{[0-9,] }");
int[][] array = pattern.matcher(input).results()
.map(matchResult -> matchResult.group().replaceAll("[{}]", ""))
.map(numberAsText -> Arrays.stream(numberAsText.split(",")).mapToInt(Integer::parseInt).toArray())
.toArray(int[][]::new);
Just as the others pointed out - if you have the possibility to change shape of input - I would also advice to use JSON's array and parse it using JSON parser which would make it much easier and more clean.