Sort using a custom comparator: Difference between revisions

m
Line 2,220:
Arrays.sort(strings) { first, second ->
val lengthDifference = second.length - first.length
if (lengthDifference == 0) first.lowercase().compareTo(second.lowercase(), true) else lengthDifference
}
 
Line 2,238:
 
// sort by content first then by length => no need for a custom comparator since sortedByDescending is stable
val sorted = strings.sortedsortedBy { it.lowercase() }.sortedByDescending { it.length }
 
println("Sorted: $sorted")
}</lang>
Line 2,252 ⟶ 2,253:
kotlin.Comparator { a, b ->
compareValues(b.length, a.length).let {
if (it == 0) compareValues(a.lowercase(), b.lowercase())
else it
}
})
 
println("Sorted: $sorted")
}</lang>
 
 
Faster when computing length and lowercase only once per value ([[wp:Schwartzian transform|Schwartzian transform]]):
 
<lang kotlin>fun main(args: Array<String>) {
Line 2,266 ⟶ 2,268:
println("Unsorted: $strings")
 
val sorted = strings.map { Triple (it, it.length, it.lowercase()) }.sortedWith (
kotlin.Comparator { a, b ->
compareValues(b.second, a.second).let {
if (it == 0) compareValues(a.third, b.third)
else it
}
}).map { it.first }
 
Anonymous user