Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

kotlin - Count sum of all list elements until condition is satisfied

I faced the following problem: I have a list of objects. Let it be objects of the class Test:

data class Test(
    var status: String, // Can be EXPIRED, WAIT
    var amount: Float
)

The array is sorted, there are objects with the status EXPIRED in the beginning and after objects with the status WAIT located. I need to calculate the sum of all elements with the status EXPIRED (if they exist) and add to this sum amount of the first object with the type WAIT (if it exists). Now I have the following code:

 private fun getRestructuringAmountToPay(): Float {
        var i = 0
        var sum = 0F
        list?.forEachIndexed { iter, el ->
            if (el.status != RestructingItemStatus.WAIT) {
                i = iter
                sum += el.amount ?: 0F
            }
        }
        if (i + 1 < (list?.size ?: 0)) {
            sum += list?.get(i+1)?.amount ?: 0F
        }
        return sum
    }

But is there any way to improve this code and make it Kotlin-pretty? Thanks in advance for any help!

question from:https://stackoverflow.com/questions/65906804/count-sum-of-all-list-elements-until-condition-is-satisfied

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

since your list is sorted and EXPIRED items are first you can use firstOrNull to find the first item with status == WAIT

while you iterate over EXPIRED items you can use a simple variable to sum the amount and when you found the first WAIT item just assign the sum to amount

 var sum: Float = 0f
 list.firstOrNull {
     sum += it.amount
     it.status == "WAIT"
 }?.apply {
     this.amount = sum
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...