Skip to content

Commit 49b42d7

Browse files
committed
BAEL-2218 Example of sorting in Kotlin
1 parent b57a14d commit 49b42d7

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.baeldung.sorting
2+
3+
import kotlin.comparisons.*
4+
5+
fun sortMethodUsage() {
6+
val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6)
7+
sortedValues.sort()
8+
println(sortedValues)
9+
}
10+
11+
fun sortByMethodUsage() {
12+
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
13+
sortedValues.sortBy { it.second }
14+
println(sortedValues)
15+
}
16+
17+
fun sortWithMethodUsage() {
18+
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
19+
sortedValues.sortWith(compareBy({it.second}, {it.first}))
20+
println(sortedValues)
21+
}
22+
23+
fun <T : kotlin.Comparable<T>> getSimpleComparator() : Comparator<T> {
24+
val ascComparator = naturalOrder<T>()
25+
return ascComparator
26+
}
27+
28+
fun getComplexComparator() {
29+
val complexComparator = compareBy<Pair<Int, String>>({it.first}, {it.second})
30+
}
31+
32+
fun nullHandlingUsage() {
33+
val sortedValues = mutableListOf(1 to "a", 2 to null, 7 to "c", 6 to "d", 5 to "c", 6 to "e")
34+
sortedValues.sortWith(nullsLast(compareBy { it.second }))
35+
println(sortedValues)
36+
}
37+
38+
fun extendedComparatorUsage() {
39+
val students = mutableListOf(21 to "Helen", 21 to "Tom", 20 to "Jim")
40+
41+
val ageComparator = compareBy<Pair<Int, String?>> {it.first}
42+
val ageAndNameComparator = ageComparator.thenByDescending {it.second}
43+
println(students.sortedWith(ageAndNameComparator))
44+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.sorting
2+
3+
import org.junit.jupiter.api.Test
4+
5+
import org.junit.jupiter.api.Assertions.*
6+
7+
class SortingExampleKtTest {
8+
9+
@Test
10+
fun naturalOrderComparator_ShouldBeAscendingTest() {
11+
val resultingList = listOf(1, 5, 6, 6, 2, 3, 4).sortedWith(getSimpleComparator())
12+
assertTrue(listOf(1, 2, 3, 4, 5, 6, 6) == resultingList)
13+
}
14+
}

0 commit comments

Comments
 (0)