高阶函数
1.map
arrayOf(1, 2, 3).map { i: Int -> i * 10 }.forEach(::println)
2.flatMap
listOf(listOf("a", "b"), listOf("c", "d")).flatMap { i: List<String> -> i.asIterable() }.forEach(::println)
println("----------")
arrayOf(1..3, 1..5).flatMap { i: IntRange -> i.asIterable() }.forEach(::println)
3.fold
val foldResult1 = arrayOf(1, 2, 3).fold(10, { a, b -> a + b })
val foldResult2 = arrayOf(1, 2, 3).fold(10, { a, b -> a * b })
println(foldResult1)
println(foldResult2)
4.reduce
val reduceResult1 = arrayOf(1, 2, 3, 4).reduce { acc, i -> acc + i }
val reduceResult2 = arrayOf(1, 2, 3, 4).reduce { acc, i -> acc * i }
val reduceResult3 = arrayOf("a", "b", "c", "d").reduce { acc, i -> "$acc,$i" }
println(reduceResult1)
println(reduceResult2)
println(reduceResult3)
5.joinToString
val joinToStringResult1 = arrayOf("a", "b", "c", "d").joinToString { i -> i }
val joinToStringResult2 = arrayOf("a", "b", "c", "d").joinToString(separator = "#", prefix = "[前缀]", postfix = "[后缀]", limit = 3, truncated = "[省略号]") { i -> i }
println(joinToStringResult1)
println(joinToStringResult2)
6.filter
arrayOf(1, 2, 3, 0, 4).filter { i -> i >= 2 }.forEach(::println)
println("----------")
arrayOf(1, 2, 3, 0, 4).filterIndexed { index, i -> index >= 2 }.forEach(::println)
7.takeWhile
arrayOf(4, 3, 2, 5).takeWhile { i -> i > 2 }.forEach(::println)