'Amstrong number using lambda Expressions in Java 8
I am fairly new to functional programming. Following is my code to check the sum of powered digits(Arsmstrong number check). Number is an input for example: 370 which is an amstrong number, the return statement has to return the sum as 370. I need to achieve this by functional programming only. How can I change the value 3 to be dynamic and equal to the number of digits.
return String.valueOf(number).chars().mapToObj(e -> Character.getNumericValue(e)).collect(Collectors.toList())
.stream()
.reduce(0, (sum,value) -> {
sum += (int)Math.pow(value, 3);
return sum;
});
Solution 1:[1]
Here is an IntPredicate that can test for an Armstrong number.
- get the number of digits (in this case exponent) using
Math.log10 - stream the values divided by ten to expose the least significant digit of each quotient.
- reduce the stream to a sum by raising last digit (via
quotient % 10) to the number of digits - returns a boolean on the result of comparing the original value to the sum.
IntPredicate isArmstrong = val -> {
int exp = (int) Math.log10(val) + 1;
return IntStream.iterate(val, v -> v > 0, v -> v / 10)
.reduce(0, (sum, quotient) -> sum + (int) Math
.pow(quotient % 10, exp)) == val;
};
System.out.println(isArmstrong.test(153));
System.out.println(isArmstrong.test(8208));
System.out.println(isArmstrong.test(9923));
prints
true
true
false
This can also be used to filter a stream of ints. ...filter(isArmstrong)... and return the values in an array, collection, or just printing as they pass thru the filter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
