<@U1DCM39JR> There’s no function here <https://kot...
# announcements
a
@supaham There’s no function here https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html that returns
List<T>
or
Iterator<T>
and does what you’d like, so I doubt there is one. Here are two ways I could think of to implement it though:
Copy code
inline fun <T, R : Comparable<R>> Iterable<T>.allMaxBy(selector: (T) -> R): List<T>? {
    return map(selector).max()?.let { best -> filter { selector(it) == best } }
}

inline fun <T, R : Comparable<R>> Iterable<T>.allMaxBy(selector: (T) -> R): List<T>? {
    return groupBy(selector).run { get(keys.max()) }
}
s
That is a lot simpler than I was thinking. Thanks! 🙂
a
You’re welcome, note that the second version looks nicer (you might want to inline it in your source code and get rid of the
allMaxBy
function altogether), but the first version should actually perform better (it doesn’t allocate as much stuff as the second version)