This is the second solution to find the sum of digits from a given alpha numeric value by using a functional interface with single abstract method and lambda expression. Internally it uses String and Character class methods.
import java.util.Scanner;
public class SumofDigitsInAlphanumeric {
// Define the functional interface with single abstract method.
interface SumOfDigitsInAlphanumeric {
public int sumOfDigts(String strVal);
}
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner inpAlphaNumeric = new Scanner(System.in);
// Input an alphanumeric value
System.out.print("Enter an alphanumeric value=");
String strValue = inpAlphaNumeric.next();
System.out.println("The String value is=" + strValue);
/* Define the Lambda expression for the user defined functional interface */
SumOfDigitsInAlphanumeric ds = ((strVal) -> {
int lenOfStr = strVal.length(), sum = 0;
while (--lenOfStr >= 0)
if (Character.isDigit(strVal.charAt(lenOfStr)))
sum += Character.getNumericValue(strVal.charAt(lenOfStr));
return sum;
});
System.out.println("The sum of digits in the given string is " + strValue + " is= " + ds.sumOfDigts(strValue));
System.out.println("The sum of digits in an other string is = " + ds.sumOfDigts("Jw2@#5Yu7"));
}
}
OUTPUT:
Enter an alphanumeric value=Jh7%e3Q8@
The String value is=Jh7%e3Q8@
The sum of digits in the given string is Jh7%e3Q8@ is= 18
The sum of digits in an other string is = 14

Leave a comment