diff --git a/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt b/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt new file mode 100644 index 0000000000..2309d23c36 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt @@ -0,0 +1,44 @@ +package com.baeldung.sorting + +import kotlin.comparisons.* + +fun sortMethodUsage() { + val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6) + sortedValues.sort() + println(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) +} + +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) +} + +fun > getSimpleComparator() : Comparator { + val ascComparator = naturalOrder() + return ascComparator +} + +fun getComplexComparator() { + val complexComparator = compareBy>({it.first}, {it.second}) +} + +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) +} + +fun extendedComparatorUsage() { + val students = mutableListOf(21 to "Helen", 21 to "Tom", 20 to "Jim") + + val ageComparator = compareBy> {it.first} + val ageAndNameComparator = ageComparator.thenByDescending {it.second} + println(students.sortedWith(ageAndNameComparator)) +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt new file mode 100644 index 0000000000..8a94e29c2f --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt @@ -0,0 +1,14 @@ +package com.baeldung.sorting + +import org.junit.jupiter.api.Test + +import org.junit.jupiter.api.Assertions.* + +class SortingExampleKtTest { + + @Test + fun naturalOrderComparator_ShouldBeAscendingTest() { + val resultingList = listOf(1, 5, 6, 6, 2, 3, 4).sortedWith(getSimpleComparator()) + assertTrue(listOf(1, 2, 3, 4, 5, 6, 6) == resultingList) + } +} \ No newline at end of file