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,528
  • 11
  • 29
Artem
  • 358
  • 3
  • 15

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
  • 19,604
  • 6
  • 47
  • 65
6
 int[] result = String.valueOf(numbersToArray)
            .chars()
            .map(Character::getNumericValue)
            .toArray();
Eugene
  • 117,005
  • 15
  • 201
  • 306
3

Using java-8 one can do:

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