5

I have one number, for example "1256", how can I convert it into an Array?

Actually, I use a constructor of class where I stock it.

public SecretBlock(int numbersToArray) {
    this.arrayOfNumbers = new int[AMOUNT];
    for (int i = AMOUNT - 1; i >= 0; i--) {
        this.arrayOfNumbers[i] = numbersToArray % 10;
        numbersToArray /= 10;
    }
}

Is there any fine/ adequate solution that may use Java 8 Stream?

Ron Nabuurs
  • 1,492
  • 10
  • 28
Artem
  • 314
  • 3
  • 13

3 Answers3

6

Your current solution is probably the most concise, but if you really want to use Java8 you can make use of following snippet:

int[] array = Arrays.stream(String.valueOf(numbersToArray).split(""))
    .mapToInt(Integer::parseInt)
    .toArray();
Lino
  • 18,775
  • 5
  • 46
  • 62
6
 int[] result = String.valueOf(numbersToArray)
            .chars()
            .map(Character::getNumericValue)
            .toArray();
Eugene
  • 110,516
  • 12
  • 173
  • 277
3

Using java-8 one can do:

Pattern.compile("")
       .splitAsStream(String.valueOf(numbersToArray))
       .mapToInt(Integer::parseInt)
       .toArray();
Ousmane D.
  • 52,579
  • 8
  • 80
  • 117
  • 1
    Aah the `Pattern`. I always forget about that one. That is a very clean solution :) +1 – Lino Jun 01 '18 at 09:26