Should max()/maxBy()/maxWith() return the last largest element?

If you want to get an album with the maximum number of plays and when there’s a tie, with the minimum number of songs, it would be much more easy, efficient, and reliable to construct a custom comparator:

data class Album(val noOfSongs: Int, val noOfPlays: Int)

fun main() {
//sampleStart
    val albums = listOf(Album(15, 20), Album(9, 15), Album(10, 20)).shuffled()
    val comparator = compareBy<Album> { it.noOfPlays }.thenByDescending { it.noOfSongs }
    
    println(albums.maxWith(comparator))   
//sampleEnd
}
2 Likes