Skip to content

[sorted-functions] using sortWith in code #961

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,43 +1,48 @@
package com.baeldung.sorting

import org.slf4j.LoggerFactory

val log = LoggerFactory.getLogger("SortingExample")

fun sortMethodUsage() {
val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6)
sortedValues.sort()
println(sortedValues)
log.info("$sortedValues")
}

fun sortByMethodUsage() {
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
sortedValues.sortBy { it.second }
println(sortedValues)
log.info("$sortedValues")
}

fun sortWithMethodUsage() {
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
sortedValues.sortWith(compareBy({it.second}, {it.first}))
println(sortedValues)
sortedValues.sortWith(compareBy({ it.second }, { it.first }))
log.info("$sortedValues")
}

fun <T : kotlin.Comparable<T>> getSimpleComparator() : Comparator<T> {
fun <T : kotlin.Comparable<T>> getSimpleComparator(): Comparator<T> {
val ascComparator = naturalOrder<T>()
return ascComparator
}

fun getComplexComparator() {
val complexComparator = compareBy<Pair<Int, String>>({it.first}, {it.second})
print("Complex comparator result: $complexComparator" )
val complexComparator = compareBy<Pair<Int, String>>({ it.first }, { it.second })
log.info("Complex comparator result: $complexComparator")
}

fun nullHandlingUsage() {
val sortedValues = mutableListOf(1 to "a", 2 to null, 7 to "c", 6 to "d", 5 to "c", 6 to "e")
sortedValues.sortWith(nullsLast(compareBy { it.second }))
println(sortedValues)
log.info("$sortedValues")
}

fun extendedComparatorUsage() {
val students = mutableListOf(21 to "Helen", 21 to "Tom", 20 to "Jim")

val ageComparator = compareBy<Pair<Int, String?>> {it.first}
val ageAndNameComparator = ageComparator.thenByDescending {it.second}
println(students.sortedWith(ageAndNameComparator))
val ageComparator = compareBy<Pair<Int, String?>> { it.first }
val ageAndNameComparator = ageComparator.thenByDescending { it.second }
students.sortWith(ageAndNameComparator)
log.info("$students")
}