Issue
I want to sum digits from eg. String
like "153" till index 2 and receive result 6
because of 1+5=6.
In a normal way, I would use the classic loop solution like with check whether current index is lower than 2:
static int sum(String s){
int sum = 0;
for(int i = 0; i < s.length() ; i++){
if( Character.isDigit(s.charAt(i)) ){
sum = sum + Character.getNumericValue(s.charAt(i));
}
}
return sum;
}
Above approach works as it should but I want to rewrite this logic to Java stream
approach.
I have an implementation like:
public static int sumDigitsTillIndex(String number) {
return IntStream.range(0, number.length())
.filter(i -> i < 2)
.map(number::charAt)
.sum();
}
and for this with argument 153 I am receiving 102 what is a surprise for me.
I have found another, smiliar solution like:
return String
.valueOf(number)
.chars()
.map(Character::getNumericValue)
.sum();
which is summing numbers properly but with additional filter
method like:
.filter(index -> number.charAt(index) < 2)
I am receiving
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 49
I will be grateful for suggestion on how to fix these two above solutions and receive functional approach which will sum up digits from String till particular index.
Solution
You can do:
number.chars()
.limit(2)
.map(Character::getNumericValue)
.sum();
or
number.substring(0, 2)
.chars()
.map(Character::getNumericValue)
.sum();
Answered By - Hadi J
Answer Checked By - David Goodson (JavaFixing Volunteer)