The set operation of a function
filter
Filter iterates through the collection and places each element into the lambda, adding a new collection if it matches the expression, or discarding the element otherwise
Similarly, filterIndexed indexed filters, filterNot, filter all filters that do not meet the criteria
val test = listOf(1.3.5.7.9)
// The filter function iterates through the collection and selects the elements that return true when applied to the given lambda
println("Anything greater than 5${test.filter { it > 5 }}")
Copy the code
The output
Is greater than5The number of [7.9]
Copy the code
map
Map’s function is: I understand that the corresponding transformation should be, traversing each data in the collection, then performing data transformation through lambda, adding new collection and returning
val test = listOf(1.3.5.7.9)
// The map function iterates through each data in the collection, then transforms the data through lambda, adds the new collection and returns
println("Convert all data in the collection to a string${test.map { "haha$it" }}")
Copy the code
The output
Convert all data in the collection to a string [haha1, haha3, haha5, haha7, haha9]Copy the code
all & any & count & find
val test = listOf(1.3.5.7.9)
// all Determines whether all of the criteria for a lambda expression are met
println("Whether all match >10${test.all { it > 10 }}")
// any determines whether data exists that matches the conditions of a lambda expression
println("Does there exist >8${test.any { it > 8 }}")
// count Gets the number of data that matches a lambda expression condition
println("The number of numbers greater than 5${test.count { it > 5 }}")
// find retrieves the first data that matches a lambda expression condition
println("The first one is greater than 5${test.find { it > 5 }}")
println("The last one is greater than 5${test.findLast { it > 5 }}")
Copy the code
The output
Do they all match >10 falseDoes it exist >8 trueIs greater than5The number of2The first one is greater than5 7The last one is greater than5 9
Copy the code
groupBy
GroupBy iterates through each element, returns the element to lambda, generates a key according to lambda’s rules, and returns the element as a value in a new map
val test1 = listOf("a"."ab"."b"."bc")
// groupBy iterates through each element, returns the element to lambda, generates a key according to lambda's rules, and returns the element as a value in a new map
println("Group by initial letter${test1.groupBy{it[0]}}")
Copy the code
The output
Group by first letter {a=[a, ab], b=[b, BC]}Copy the code
partition
Only Boolean conditions are supported. First indicates that the conditions are met. Second indicates that the conditions are not met
val test1 = listOf("a"."ab"."b"."bc")
println("Satisfied")
test1.partition { it.length > 1 }.first.forEach { print("$it, "") }
println()
println("Not meeting the criteria.")
test1.partition { it.length > 1 }.second.forEach { print("$it, "")}Copy the code
The output
Ab, BC, A, B,Copy the code
flatMap
The flatMap function: first iterates through each element, transforms the elements according to the lambda expression, and then merges the transformed lists into a new list
// The flatMap first iterates through each element and transforms the elements according to the lambda expression, then merges the transformed lists into a new list
println(test1.flatMap { it.toList() })
Copy the code
The output
[a, a, b, b, b, c]
Copy the code
sortedBy
SortedBy is sort if you have time to look at the source code
val test2 = listOf(3.2.4.6.7.1)
// Sort low --> high
println(test2.sortedBy { it })
// Sort high --> low
println(test2.sortedByDescending { it })
Copy the code
The output
[1.2.3.4.6.7]
[7.6.4.3.2.1]
Copy the code
take & slice
val test3 = listOf(3.2.4.6.7.1)
// Get the first three elements and return them as a new collection
println(test3.take(3))
// Get the specified index, get the element, re-form the collection and return it
println(test3.slice(IntRange(2.4)))
Copy the code
reduce
Reduce functions: All elements of a set are passed in to achieve the cumulative operation effect of the data set.
val test4 = listOf("a"."ab"."b"."bc")
// The reduce function takes all the elements of a set and passes them through the operation function to achieve the cumulative operation effect of the data set.
println(test4.reduce { acc, name -> "$acc$name" })
Copy the code
The output
aabbbc
Copy the code
Lazy sequence operation
When some collection functions make chain calls, each function saves the result of the call as a new temporary list. Therefore, a large number of chain operations will create a large number of intermediate variables, which can cause performance problems. To solve the performance problems, you can change the chain operations to a sequence
Call the extension function asSequence to convert any set to a sequence, and call toList to do the reverse
// a chain call to the function
println("Collection calls show names with ages greater than 10${
testList.filter { it.age > 10 }
.map { it.name }}")
// The sequence operation of the function
println("The collection call shows name1 with age greater than 10${
testList.asSequence()
.filter { it.age > 10 }
.map { it.name }.toList()}")
Copy the code
// Intermediate operation // terminal operationtestList.asSequence(). filter {.. }.map {.. }.toList()Copy the code
The sequential approach improves performance by avoiding a large number of intermediate collections
Delay calculation
fun lateAdd(a: Int, b: Int): () - >Int {
fun add(a): Int {
return a + b
}
return ::add
}
fun main(a) {
val add = lateAdd(1.2)
println(add.invoke())
}
Copy the code
LateAdd defines a local function that returns a reference to ga and uses invoke on the result to achieve delayed use
fold
Fold: You can set an initial value, iterate through each element, put it into a lambda, and return
val test5 = listOf("ab"."abc"."bd"."bcs")
println(
"Use of fold ==${
test5.fold("Initial value") { acc, s ->
acc + s
}
}"
)
Copy the code
The output
Use of fold == initial value ababCBDBcsCopy the code