TrueCode :
I have a list of strings that looks something like this :
- 2010 1 11.45
- 2010 2 09.50
- 2010 3 15.00
- .
- .
- .
- 2019 12 11.10
(the list is a list of spends per month between the years of 2010 - 2019)
I have separated the list into 3 lists for each value such as :
for(....){
val part = list.get(i).split(" ")
val year = parts[0]
val month = parts[1]
val spend = parts[2]
yearlist.add(year)
monthlist.add(month)
spendlist.add(spend)
}
Now my issue is that I want to find the year with the highest spend total. How would I add all of the spends for each year?
I have tried the following method however this gives me an IndexOutOfBounds Exception:
var totalspend = 0
for(i in 0..yearlist.size-1){
if(yearlist[i]==yearlist[i+1]){//i get an error here
totalspend = totalspend + spendlift[i]
}
else if(yearlist[i]!=yearlist[i+1]){
totalspend = totalspend + spendlift[i]
spendforyear.add(totals(year[i], totalspend))
totalspend = 0.0
}
}
I assume the error is because i cant compare the final yearlist value with yearlist[i+1] as i+1 is out of bounds.
How would i go about solving this?
Mohamed Mohsin :
I would suggest saving the year
, month
and spend
in a data class
and then use collection functions:
data class Report(val year: String, val month: String, val spend: Double)
fun main() {
val reports = listOf(
Report("2010", "1", 11.45),
Report("2010", "2", 09.50),
Report("2010", "3", 15.00),
Report("2019", "12", 11.10)
)
val groupedReports = reports.groupBy { it.year }
val mostSpending = groupedReports.maxBy { it.value.sumByDouble { report -> report.spend } }
println(mostSpending?.key) // year with the most spending
println(mostSpending?.value?.sumByDouble { it.spend }) // the spending on that year
}