-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
  • 118,400
  • 24
  • 176
  • 257

1 Answers1

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