This is the third solution to find the sum of digits of an integer value[s]. This solution uses the map(), and reduce() methods of Arrays stream.
import java.util.Arrays;
import java.util.Scanner;
public class SumofdgtsUsingStream {
public static void main(String[] args) {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner inpInt = new Scanner(System.in);
// Input a number
System.out.print("Enter a number=");
long numValue = inpInt.nextLong();
System.out.println("The given number is is=" + numValue);
// Convert given number to array of chars
// Apply stream using map and reduce methods to find sum of all digits
String[] strArray = String.valueOf(numValue).split("\\s*");
Integer sumDigits = Arrays.stream(strArray).map(c -> Integer.parseInt(c)).reduce(0, (a, b) -> a + b);
System.out.println("The sum of Digits in the given " + numValue + " is " + sumDigits);
}
}
Output:
Enter a number=74019
The given number is is=74019
The sum of Digits in the given 74019 is 21

Leave a comment