Add samples for mapNotNull, find, getOrNull functions
This commit is contained in:
committed by
Abduqodiri Qurbonzoda
parent
62df2b3195
commit
41d5615608
@@ -532,6 +532,15 @@ class Collections {
|
||||
assertPrints(numbers.map { it * it }, "[1, 4, 9]")
|
||||
}
|
||||
|
||||
@Sample
|
||||
fun mapNotNull() {
|
||||
val strings: List<String> = listOf("12a", "45", "", "3")
|
||||
val ints: List<Int> = strings.mapNotNull { it.toIntOrNull() }
|
||||
|
||||
assertPrints(ints, "[45, 3]")
|
||||
assertPrints(ints.sum(), "48")
|
||||
}
|
||||
|
||||
@Sample
|
||||
fun flatMap() {
|
||||
val list = listOf("123", "45")
|
||||
@@ -770,6 +779,27 @@ class Collections {
|
||||
val emptyList = emptyList<Int>()
|
||||
assertPrints(emptyList.elementAtOrElse(0) { "no int" }, "no int")
|
||||
}
|
||||
|
||||
@Sample
|
||||
fun find() {
|
||||
val numbers = listOf(1, 2, 3, 4, 5, 6, 7)
|
||||
val firstOdd = numbers.find { it % 2 != 0 }
|
||||
val lastEven = numbers.findLast { it % 2 == 0 }
|
||||
|
||||
assertPrints(firstOdd, "1")
|
||||
assertPrints(lastEven, "6")
|
||||
}
|
||||
|
||||
@Sample
|
||||
fun getOrNull() {
|
||||
val list = listOf(1, 2, 3)
|
||||
assertPrints(list.getOrNull(0), "1")
|
||||
assertPrints(list.getOrNull(2), "3")
|
||||
assertPrints(list.getOrNull(3), "null")
|
||||
|
||||
val emptyList = emptyList<Int>()
|
||||
assertPrints(emptyList.getOrNull(0), "null")
|
||||
}
|
||||
}
|
||||
|
||||
class Sorting {
|
||||
|
||||
@@ -325,6 +325,14 @@ class Maps {
|
||||
assertPrints(map2, "{beverage=2.7$, meal=12.4$}")
|
||||
}
|
||||
|
||||
@Sample
|
||||
fun mapNotNull() {
|
||||
val map = mapOf("Alice" to 20, "Tom" to 13, "Bob" to 18)
|
||||
val adults = map.mapNotNull { (name, age) -> name.takeIf { age >= 18 } }
|
||||
|
||||
assertPrints(adults, "[Alice, Bob]")
|
||||
}
|
||||
|
||||
@Sample
|
||||
fun mapToSortedMap() {
|
||||
val map = mapOf(Pair("c", 3), Pair("b", 2), Pair("d", 1))
|
||||
|
||||
Reference in New Issue
Block a user