JAVA-101 Split Core Kotlin

This commit is contained in:
mikr
2020-06-08 00:22:04 +02:00
parent 0130ae560f
commit 73e169d1eb
48 changed files with 136 additions and 27 deletions

View File

@@ -10,3 +10,4 @@ This module contains articles about core Kotlin collections.
- [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection)
- [Collection Transformations in Kotlin](https://www.baeldung.com/kotlin-collection-transformations)
- [Difference between fold and reduce in Kotlin](https://www.baeldung.com/kotlin/fold-vs-reduce)
- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort)

View File

@@ -0,0 +1,42 @@
package com.baeldung.sorting
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,13 @@
package com.baeldung.sorting
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
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)
}
}