Skip to content

Commit d0cbb91

Browse files
authored
Merge pull request #961 from sk1418/sorted-functions
[sorted-functions] using sortWith in code
2 parents 23bb604 + 2f66492 commit d0cbb91

File tree

1 file changed

+16
-11
lines changed
  • core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/sorting

1 file changed

+16
-11
lines changed
Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,48 @@
11
package com.baeldung.sorting
22

3+
import org.slf4j.LoggerFactory
4+
5+
val log = LoggerFactory.getLogger("SortingExample")
6+
37
fun sortMethodUsage() {
48
val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6)
59
sortedValues.sort()
6-
println(sortedValues)
10+
log.info("$sortedValues")
711
}
812

913
fun sortByMethodUsage() {
1014
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
1115
sortedValues.sortBy { it.second }
12-
println(sortedValues)
16+
log.info("$sortedValues")
1317
}
1418

1519
fun sortWithMethodUsage() {
1620
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
17-
sortedValues.sortWith(compareBy({it.second}, {it.first}))
18-
println(sortedValues)
21+
sortedValues.sortWith(compareBy({ it.second }, { it.first }))
22+
log.info("$sortedValues")
1923
}
2024

21-
fun <T : kotlin.Comparable<T>> getSimpleComparator() : Comparator<T> {
25+
fun <T : kotlin.Comparable<T>> getSimpleComparator(): Comparator<T> {
2226
val ascComparator = naturalOrder<T>()
2327
return ascComparator
2428
}
2529

2630
fun getComplexComparator() {
27-
val complexComparator = compareBy<Pair<Int, String>>({it.first}, {it.second})
28-
print("Complex comparator result: $complexComparator" )
31+
val complexComparator = compareBy<Pair<Int, String>>({ it.first }, { it.second })
32+
log.info("Complex comparator result: $complexComparator")
2933
}
3034

3135
fun nullHandlingUsage() {
3236
val sortedValues = mutableListOf(1 to "a", 2 to null, 7 to "c", 6 to "d", 5 to "c", 6 to "e")
3337
sortedValues.sortWith(nullsLast(compareBy { it.second }))
34-
println(sortedValues)
38+
log.info("$sortedValues")
3539
}
3640

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

40-
val ageComparator = compareBy<Pair<Int, String?>> {it.first}
41-
val ageAndNameComparator = ageComparator.thenByDescending {it.second}
42-
println(students.sortedWith(ageAndNameComparator))
44+
val ageComparator = compareBy<Pair<Int, String?>> { it.first }
45+
val ageAndNameComparator = ageComparator.thenByDescending { it.second }
46+
students.sortWith(ageAndNameComparator)
47+
log.info("$students")
4348
}

0 commit comments

Comments
 (0)