Sort using a custom comparator: Difference between revisions

Content added Content deleted
Line 2,263: Line 2,263:


<lang kotlin>fun main(args: Array<String>) {
<lang kotlin>fun main(args: Array<String>) {
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
println("Unsorted: $strings")
println("Unsorted: $strings")


val sorted = strings.map { Pair(it, it.length) }.sortedWith (
val sorted = strings.map { Triple (it, it.length, it.lowercase()) }.sortedWith (
kotlin.Comparator { a, b ->
kotlin.Comparator { a, b ->
compareValues(b.second, a.second).let {
compareValues(b.second, a.second).let {
if (it == 0) compareValues(a.first, b.first)
if (it == 0) compareValues(a.third, b.third)
else it
else it
}
}
}).map { it.first }
}).map { it.first }
println("Sorted: $sorted")
println("Sorted: $sorted")
}
}</lang>
</lang>




{{out}}
{{out}}
<pre>Unsorted: [Here, are, some, sample, strings, to, be, sorted]
<pre>Unsorted: [Here, are, some, sample, strings, to, be, sorted]
Sorted: [strings, sample, sorted, Here, some, are, be, to]</pre>
Sorted: [strings, sample, sorted, Here, some, are, be, to]</pre>


=={{header|Lua}}==
=={{header|Lua}}==