This is the third solution to check whether a given number is Armstrong number or not. This program uses the map() and reduce() methods of java streams.
import java.util.ArrayList;
import java.util.Scanner;
public class ArmstrongNumberUsingStream {
public static void main(String args[]) {
// To check whether a give number is Armstrong number or not
Scanner inpInt = new Scanner(System.in);
System.out.print("Enter a number to check for Armstrong or not=");
int inpNum = inpInt.nextInt();
System.out.println("The given number is=" + inpNum);
String strVal = String.valueOf(inpNum);
ArrayList<Integer> arrOfDigits = new ArrayList<Integer>();
for (char ch : strVal.toCharArray())
arrOfDigits.add(Character.getNumericValue(ch));
System.out.println("The list of Digits are= " + arrOfDigits);
// Applying map and reduce method to find our sum of cubes
int sumOfCubes = arrOfDigits.stream().map(a -> a * a * a).reduce(0, (x, y) -> x + y);
if (sumOfCubes == inpNum)
System.out.println("The given number " + inpNum + " is an ArmstrongNumber");
else
System.out.println("The given number " + inpNum + " is not an ArmstrongNumber");
}
}
OUTPUT-
Enter a number to check for Armstrong or not=407
The given number is=407
The list of Digits are= [4, 0, 7]
The given number 407 is an ArmstrongNumber

Leave a comment