Merge pull request #5559 from laurentiud/master

BAEL-2218 Example of sorting in Kotlin
This commit is contained in:
José Carlos Valero Sánchez 2018-10-28 20:40:50 +00:00 committed by GitHub
commit 67b02d7277
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 0 deletions

View File

@ -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 <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})
}
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<Pair<Int, String?>> {it.first}
val ageAndNameComparator = ageComparator.thenByDescending {it.second}
println(students.sortedWith(ageAndNameComparator))
}

View File

@ -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)
}
}