-1

Suppose

Example1: number is 37 Sum of numbers is 3+7= 10

Ex2: Number is 1000 Sum of numbers is 1+0+0+0 = 1.

My first approach was converting number to string and then char array. With that I could use stream in which I converted chars to their int values which let me performed sum.

But is there any utility method in Stream API which could improve it?

Pshemo
  • 122,468
  • 25
  • 185
  • 269

1 Answers1

3
    public long getSumOfDigits(int number)
    {
        return Stream.of(String.valueOf(number).split(""))
                .collect(Collectors.summarizingInt(Integer::parseInt))
                .getSum();
    }
pcsutar
  • 1,715
  • 2
  • 9
  • 14