Split str on , and map the elements into integers using Integer#parseInt.
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String str = "12,1,222,55";
int[] array = Arrays.stream(str.split(","))
.mapToInt(Integer::parseInt)
.toArray();
System.out.println(Arrays.toString(array));
}
}
Output:
[12, 1, 222, 55]
Alternatively,
Extract the integer strings using the pattern, \d+ (i.e. one or more digits) and map them into integers using Integer#parseInt.
int[] array = Pattern.compile("\\d+")
.matcher(line)
.results()
.map(MatchResult::group)
.mapToInt(Integer::parseInt)
.toArray();
Demo:
import java.util.Arrays;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "12,1,222,55";
int[] array = Pattern.compile("\\d+")
.matcher(str)
.results()
.map(MatchResult::group)
.mapToInt(Integer::parseInt)
.toArray();
System.out.println(Arrays.toString(array));
}
}
Output:
[12, 1, 222, 55]
,and covert element to int and store an array.