https://kotlinlang.org logo
#announcements
Title
# announcements
a

arekolek

08/14/2017, 6:10 PM
@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

supaham

08/14/2017, 6:12 PM
That is a lot simpler than I was thinking. Thanks! 🙂
a

arekolek

08/14/2017, 6:21 PM
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)
2 Views