How to get the separate digits of an int number?

前端 未结 30 1942
陌清茗
陌清茗 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:30

    Since I don't see a method on this question which uses Java 8, I'll throw this in. Assuming that you're starting with a String and want to get a List, then you can stream the elements like so.

    List digits = digitsInString.chars()
            .map(Character::getNumericValue)
            .boxed()
            .collect(Collectors.toList());
    

    This gets the characters in the String as a IntStream, maps those integer representations of characters to a numeric value, boxes them, and then collects them into a list.

提交回复
热议问题