0

How can we split a string into an integer array without using loops?

For example:
If I have a string "12345" and I wanted to be converted to int array [1,2,3,4,5] without using loop. I know how to do it that way. Is there any built-in function that java provides that splits and converts into desired data type?

soorapadman
  • 4,451
  • 7
  • 35
  • 47
AhmerMH
  • 638
  • 7
  • 18

3 Answers3

2

If Java 8 you could use a Stream:

"A sequence of elements supporting sequential and parallel aggregate operations."

Observe:

import java.util.Arrays;
import java.util.stream.Stream;

class Main {
  public static void main(String[] args) {
    String numbersString = "12345";

    int[] numbersIntArray = Stream.of(numbersString.split("")).mapToInt(Integer::parseInt).toArray(); 

    System.out.println(Arrays.toString(numbersIntArray)); // [1, 2, 3, 4, 5]
  }
}
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
0

Java 8 You can do using Arrays util also.

String string = "12345";
int[] ints= Arrays.asList(string.split("")).stream().mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(ints));;
soorapadman
  • 4,451
  • 7
  • 35
  • 47
0

You can use recursion.

public class Test {

    static List<Integer> integerArray = new ArrayList<Integer>();
    static int strLength;
    static String s;

    public static void main(String[] args) {

        s = "12345";
        strLength = s.length();

        recursiveMe(0);

        System.out.println(integerArray.toString());
    }

    public static void recursiveMe(int n) {
        if (n < strLength) {
            integerArray.add(n, Integer.parseInt(String.valueOf(s.charAt(n))));
            recursiveMe(n + 1);
        }
    }

}
Bishan
  • 15,211
  • 52
  • 164
  • 258