How to get the separate digits of an int number?

前端 未结 30 1938
陌清茗
陌清茗 2020-11-22 03:03

I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.

How can I get

30条回答
  •  孤街浪徒
    2020-11-22 03:27

    Java 9 introduced a new Stream.iterate method which can be used to generate a stream and stop at a certain condition. This can be used to get all the digits in the number, using the modulo approach.

    int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();
    

    Note that this will get the digits in reverse order, but that can be solved either by looping through the array backwards (sadly reversing an array is not that simple), or by creating another stream:

    int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();
    

    or

    int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length - i]).toArray();
    

    As an example, this code:

    int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();
    int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();
    System.out.println(Arrays.toString(a));
    System.out.println(Arrays.toString(b));
    

    Will print:

    [0, 0, 4, 3, 2, 1]
    [1, 2, 3, 4, 0, 0]
    

提交回复
热议问题