java – How to convert the value "[1,2]" of String to an int array

Question: Question:

Please teach me how to convert the value "[1,2]" of String to an int array.

Answer: Answer:

I tried parsing using Java8 stream.

import java.util.Arrays;

public class stringToIntArray {
  public static void main(String args[]){
    String str = "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]";

    int[] arr = Arrays.stream(str.split("[, \\[\\]]"))
      .filter(s -> !s.isEmpty())
      .mapToInt(Integer::parseInt)
      .toArray();

    System.out.println(Arrays.toString(arr));
  }
}

=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Scroll to Top