This is the third solution to find sum of integers in a given alphanumeric string. This program uses the filter(), map() and reduce() methods of java streams.
import java.util.ArrayList;
import java.util.Scanner;
public class SumofIntegersInAlphanumeric {
public static void main(String args[]) {
Scanner inpScan = new Scanner(System.in);
System.out.print("Enter an Alphanumeric value= ");
String inpStr = inpScan.next();
System.out.println("The entered Alphanumeric string is= " + inpStr);
ArrayList<Character> arrChars = new ArrayList<Character>();
for (char ch : inpStr.toCharArray())
arrChars.add(ch);
System.out.println("The list of Characters are= " + arrChars);
// Apply filter, map and reduce methods on the extracted List of characters
int sumDigits = arrChars.stream().filter(c -> Character.isDigit(c)).map(x -> Character.getNumericValue(x))
.reduce(0, (a, b) -> a + b);
System.out.println("The sum of Digits in the given " + inpStr + " is " + sumDigits);
}
}
OUTPUT-
Enter an Alphanumeric value= Hr5k2L96F
The entered Alphanumeric string is= Hr5k2L96F
The list of Characters are= [H, r, 5, k, 2, L, 9, 6, F]
The sum of Digits in the given Hr5k2L96F is 22

Leave a comment