Write a program to convert string to an array of integers in java.
Example 1:
Input: String s[] = {"1","5","4","8"}
Output: int arr[] = {1,5,4,8}
Approach 1: Using for loop
Java
import java.util.Arrays;public class StringToIntegerArrayC {public static void main(String args[]) {String [] str = {"1", "5", "4", "8"};int size = str.length;int [] arr = new int [size];for(int i=0; i<size; i++) {arr[i] = Integer.parseInt(str[i]);}System.out.println(Arrays.toString(arr));}}
Approach 2: Using java 8 stream API
Java
import java.util.Arrays;public class StringToIntegerArrayC {public static void main(String args[]) {String [] str = {"1", "5", "4", "8"};int[] result = Arrays.stream(str).mapToInt(Integer::valueOf).toArray();System.out.println(Arrays.toString(result));}}
No comments:
Post a Comment