Search code examples
androidarrayskotlinarraylistoverlapping

Kotlin ArrayList overlapping value plus?


I'm using ArrayList.

I'd like to get the sum of these.

ex ) Apple = 9,300, Banana = 5,400

But these are added fluidly.

I don't know what to do.

class Statement_data(var name : String, var Value : Int) {

}

name value Apple 3,000 Apple 3,100 Banana 2,000 orange 1,500 Apple 3,200 berry 3,500 Banana 3,400 orange 1,600


Solution

  • You can filter by the name, and then use sumBy on the value. Using asSequence() is optional, but it allows it to skip copying the list contents when you filter it.

    val numApples = list.asSequence().filter { it.name == "Apple" }.sumBy(Statement_data::Value)