|
Filtering by predicate
|
val numbers = listOf("one", "two", "three", "four")
val longerThan3 = numbers.filter { it.length > 3 }
println(longerThan3)
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}
println(filteredMap)
|
let numbers = ["one", "two", "three", "four"]
let longerThan3 = numbers.filter { $0.count > 3 }
print(longerThan3)
let numbersMap = ["key1": 1, "key2": 2, "key3": 3, "key11": 11]
let filteredMap = numbersMap.filter { $0.hasSuffix("1") && $1 > 10 }
print(filteredMap)
|
val numbers = listOf("one", "two", "three", "four")
val filteredIdx = numbers.filterIndexed { index, s -> (index != 0) && (s.length < 5) }
val filteredNot = numbers.filterNot { it.length <= 3 }
println(filteredIdx)
println(filteredNot)
|
let numbers = ["one", "two", "three", "four"]
let filteredIdx = numbers
.enumerated()
.filter { $0.offset != 0 && $0.element.count < 5 }
let filteredNot = numbers.filter { $0.count > 3 }
print(filteredIdx)
print(filteredNot)
|
val numbers = listOf(null, 1, "two", 3.0, "four")
println("All String elements in upper case:")
numbers.filterIsInstance<String>().forEach {
println(it.toUpperCase())
}
|
let numbers = [nil, 1, "two", 3.0, "four"] as [Any?]
print("All String elements in upper case:")
numbers.compactMap({ $0 as? String })
.forEach { print($0.uppercased()) }
|
val numbers = listOf(null, "one", "two", null)
numbers.filterNotNull().forEach {
println(it.length) // length is unavailable for nullable Strings
}
|
let numbers = [nil, "one", "two", nil]
numbers.compactMap({ $0 }).forEach {
print($0.count)
}
|
Partitioning
|
val numbers = listOf("one", "two", "three", "four")
val (match, rest) = numbers.partition { it.length > 3 }
println(match)
println(rest)
|
var numbers = ["one", "two", "three", "four"]
let p = numbers.partition { $0.count > 3 }
print(numbers[..<p])
print(numbers[p...])
|
Testing predicates
|
val numbers = listOf("one", "two", "three", "four")
println(numbers.any { it.endsWith("e") })
println(numbers.none { it.endsWith("a") })
println(numbers.all { it.endsWith("e") })
println(emptyList<Int>().all { it > 5 }) // vacuous truth
|
let numbers = ["one", "two", "three", "four"]
print(numbers.contains { $0.hasSuffix("e") })
print(!numbers.contains { $0.hasSuffix("a") })
print(numbers.allSatisfy { $0.hasSuffix("e") })
print([Int]().allSatisfy { $0 > 5 }) // vacuous truth https://en.wikipedia.org/wiki/Vacuous_truth
|
val numbers = listOf("one", "two", "three", "four")
val empty = emptyList<String>()
println(numbers.any())
println(empty.any())
println(numbers.none())
println(empty.none())
|
let numbers = ["one", "two", "three", "four"]
let empty = [String]()
print(!numbers.isEmpty)
print(!empty.isEmpty)
print(numbers.isEmpty)
print(empty.isEmpty)
|