0

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?

1
  • Unfortunatelty this is not possible without parsing the String, which is rather complicated in this case. If you have the possibility to change the file's content to json, using a json parser will be the quickest solution. Commented Sep 21, 2021 at 9:47

2 Answers 2

5

The input stream can be parsed using String::split and Stream API:

  1. get rows splitting by comma between a pair of },{
  2. remove redundant curly brackets using String::replaceAll
  3. for each row, split by comma, convert numbers to int Stream::mapToInt and get array
  4. 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]]
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.