Kratos
Kratos

Reputation: 937

List sorting and getting elements

I have class:

class SportMan(
   val name: String,
   val points: Double,
}

and list named SportGuysList of Sportman Objects. I want to create new list from SportGuysList that has top 5 Sportman objects

Upvotes: 0

Views: 319

Answers (1)

Ilya
Ilya

Reputation: 23115

You can first sort the list by points descending, take the first 5 players from it, then sort them back by the index in the original list:

val topByPoints = SportGuysList.sortedByDescending { it.points }.take(5)
val result = topByPoints.sortedBy { SportGuysList.indexOf(it) }

If the SportGuysList is big, then searching for an index of each resulting element during sorting may take a long time, so you can remember the original index of each sportsman beside it:

val result = 
    SportGuysList.withIndex() // now we have pairs of value-index
    .sortedByDescending { it.value.points }  // sort by points
    .take(5)  // top 5
    .sortedBy { it.index } // sort back by index
    .map { it.value } // take only value from an each indexed pair

Try in Kotlin playground: https://pl.kotl.in/kMkpkIdEH

Upvotes: 2

Related Questions