filter
filter 函數(shù)讓您可以過濾集合思杯。它將過濾謂詞作為lambda參數(shù)磷雇。謂詞應(yīng)用于每個元素颓鲜。使謂詞為true的元素將在結(jié)果集合中返回尊浪。
簡單來說就是在filter 函數(shù)中設(shè)置你需要集合滿足的條件,然后返回滿足條件的元素城看。
eg:
fun filterTest() {
val numbers = listOf(1, 2, 3, 4, 5, 6, -1, -3, -4)
val positive = numbers.filter {
it > 0
}
println(positive.toString())
val negatives = numbers.filter { a -> a < 0 }
println(negatives.toString())
}
輸出結(jié)果:
[1, 2, 3, 4, 5, 6]
[-1, -3, -4]
map
通過映射擴展功能女气,您可以將轉(zhuǎn)換應(yīng)用于集合中的所有元素。它將變壓器功能作為lambda參數(shù)测柠。
eg:
fun mapTest() {
val numbers = listOf(1, 2, 3, 4, 5, 6, -1, -3, -4)
val map = numbers.map {
it * 3
}
println(map.toString())
}
打印結(jié)果:
[3, 6, 9, 12, 15, 18, -3, -9, -12]
any, all, none
作用:檢查是否存在與給定條件匹配的集合元素炼鞠。
any
如果集合包含至少一個與給定條件匹配的元素,則函數(shù)any返回true轰胁。
eg:
fun anyTest() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val anyNegative = numbers.any { it < 0 } // 2
val anyGT6 = numbers.any { it > 6 }
println("Is there any number less than 0: $anyNegative")
println("Is there any number greater than 6: $anyGT6")
}
輸出結(jié)果:
Is there any number less than 0: true
Is there any number greater than 6: false
all
如果集合中的所有元素都與給定的條件匹配谒主,則函數(shù)all返回true。
eg:
fun allTest() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val allEven = numbers.all { it % 2 == 0 } // 2
val allLess6 = numbers.all { it < 6 }
println("All numbers are even: $allEven")
println("All numbers are less than 6: $allLess6")
}
輸出結(jié)果:
All numbers are even: false
All numbers are less than 6: true
none
如果沒有與集合中給定條件匹配的元素赃阀,則函數(shù)none返回true霎肯。
eg:
fun noneTest() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val allEven = numbers.none { it % 2 == 1 } // 2
val allLess6 = numbers.none { it > 6 }
println("All numbers are even: $allEven")
println("No element greater than 6: $allLess6")
}
輸出結(jié)果:
All numbers are even: false
No element greater than 6: true
find findLast fisrt last
find和findLast函數(shù)返回與給定條件匹配的第一個或最后一個集合元素。如果沒有這樣的元素凹耙,函數(shù)返回null姿现。
例子:find findLast
fun findTest() {
val words = listOf("Lets", "find", "something", "in", "collection", "somehow") // 1
val first = words.find { it.startsWith("some") } // 2
val last = words.findLast { it.startsWith("some") } // 3
val nothing = words.find { it.contains("nothing") } // 4
println("The first word starting with \"some\" is $first")
println("The last word starting with \"some\" is $last")
println("The first word containing \"nothing\" is $nothing")
}
輸出結(jié)果:
The first word starting with "some" is something
The last word starting with "some" is somehow
The first word containing "nothing" is null
注意:它輸出的是滿足條件的以一個或者最后一個,不是集合中的第一個或最后一個
fisrt 和 **last ** 返回集合第一個和最后一個元素肖抱,也可以為其添加條件
例子: fisrt last
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val first = numbers.first() // 2
val last = numbers.last() // 3
val firstEven = numbers.first { it % 2 == 0 } // 4
val lastOdd = numbers.last { it % 2 != 0 } // 5
輸出結(jié)果:
Numbers: [1, -2, 3, -4, 5, -6]
First 1, last -6, first even -2, last odd 5
count
返回集合個數(shù)备典,或者滿足一定條件的元素個數(shù)
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val totalCount = numbers.count() // 2
val evenCount = numbers.count { it % 2 == 0 } // 3
輸出結(jié)果:
Total number of elements: 6
Number of even elements: 3
partition
函數(shù)的功能是把原來的集合根據(jù)給定的條件拆分成兩個列表,滿足條件
fun partitionTest() {
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val evenOdd = numbers.partition { it % 2 == 0 } // 2
val (positives, negatives) = numbers.partition { it > 0 } // 3
println("奇偶:$evenOdd")
println("偶數(shù):${evenOdd.first}")
println("奇數(shù) :${evenOdd.second}")
println("positives : $positives")
println("negatives : $negatives")
}
輸出結(jié)果:
奇偶:([-2, -4, -6], [1, 3, 5])
偶數(shù):[-2, -4, -6]
奇數(shù) :[1, 3, 5]
positives : [1, 3, 5]
negatives : [-2, -4, -6]
associateBy, groupBy
函數(shù)associateBy和groupBy構(gòu)建來自由指定鍵索引的集合的元素的映射意述。key在keySelector參數(shù)中定義提佣。
您還可以指定可選的valueSelector來定義將存儲在map元素值中的內(nèi)容。
區(qū)別
associateBy和groupBy之間的區(qū)別在于它們?nèi)绾问褂孟嗤逆I處理對象:
associateBy使用最后一個合適的元素作為值荤崇。
groupBy構(gòu)建所有合適元素的列表并將其放入值中拌屏。
fun associateTest() {
data class Person(val name: String, val city: String, val phone: String) //1
val people = listOf( // 2
Person("John", "Boston", "+1-888-123456"),
Person("Sarah", "Munich", "+49-777-789123"),
Person("Svyatoslav", "Saint-Petersburg", "+7-999-456789"),
Person("Vasilisa", "Saint-Petersburg", "+7-999-123456")
)
val phoneBook = people.associateBy { it.phone } // 3
val cityBook = people.associateBy(Person::phone, Person::city) // 4
val cityBook222 = people.associateBy(Person::city, Person::name) // 4
val peopleCities = people.groupBy(Person::city, Person::name) // 5
println("people:$people")
println("phoneBook:$phoneBook")
println("cityBook222:$cityBook222")
println("cityBook:$cityBook")
println("peopleCities:$peopleCities")
}
輸出結(jié)果:
people:[Person(name=John, city=Boston, phone=+1-888-123456), Person(name=Sarah, city=Munich, phone=+49-777-789123), Person(name=Svyatoslav, city=Saint-Petersburg, phone=+7-999-456789), Person(name=Vasilisa, city=Saint-Petersburg, phone=+7-999-123456)]
phoneBook:{+1-888-123456=Person(name=John, city=Boston, phone=+1-888-123456), +49-777-789123=Person(name=Sarah, city=Munich, phone=+49-777-789123), +7-999-456789=Person(name=Svyatoslav, city=Saint-Petersburg, phone=+7-999-456789), +7-999-123456=Person(name=Vasilisa, city=Saint-Petersburg, phone=+7-999-123456)}
cityBook222:{Boston=John, Munich=Sarah, Saint-Petersburg=Vasilisa}
cityBook:{+1-888-123456=Boston, +49-777-789123=Munich, +7-999-456789=Saint-Petersburg, +7-999-123456=Saint-Petersburg}
peopleCities:{Boston=[John], Munich=[Sarah], Saint-Petersburg=[Svyatoslav, Vasilisa]}
我們可以從輸出結(jié)果中看到 通過city 作為key的時候 ,兩種方式對相同key的處理
zip
zip函數(shù)將兩個給定的集合合并到一個新集合中术荤。默認情況下倚喂,結(jié)果集合包含具有相同索引的成對源集合元素。但是瓣戚,您可以定義結(jié)果集合元素的自己的結(jié)構(gòu)端圈。
fun main() {
val A = listOf("a", "b", "c","d","e") // 1
val B = listOf(1, 2, 3, 4) // 1
val resultPairs = A zip B // 2
val resultReduce = A.zip(B) { a, b -> "$a$b" } // 3
println("A to B: $resultPairs")
println("\$A\$B: $resultReduce")
}
輸出結(jié)果:
A to B: [(a, 1), (b, 2), (c, 3), (d, 4)]
$A$B: [a1, b2, c3, d4]
flatMap
flatMap將集合的每個元素轉(zhuǎn)換為可迭代對象,并構(gòu)建轉(zhuǎn)換結(jié)果的單個列表子库。轉(zhuǎn)換是用戶定義的舱权。
fun main() {
val numbers = listOf(1, 2, 3) // 1
val tripled = numbers.flatMap {
listOf(it+1) } // 2
println("Numbers: $numbers")
println("Transformed: $tripled")
}
輸出結(jié)果:
Numbers: [1, 2, 3]
Transformed: [2, 3, 4]
min,max
min和max函數(shù)返回集合中最小和最大的元素。如果集合為空仑嗅,則返回null宴倍。
fun main() {
val numbers = listOf(1, 2, 3)
val empty = emptyList<Int>()
println("Numbers: $numbers, min = ${numbers.min()} max = ${numbers.max()}") // 1
println("Empty: $empty, min = ${empty.min()}, max = ${empty.max()}") // 2
}
輸出結(jié)果 :
Numbers: [1, 2, 3], min = 1 max = 3
Empty: [], min = null, max = null
sorted sortedBy
sorted :返回根據(jù)其自然排序順序(升序)排序的集合元素列表张症。
sortedBy:根據(jù)指定選擇器函數(shù)返回的值的自然排序順序?qū)υ剡M行排序。
fun main() {
val shuffled = listOf(5, 4, 2, 1, 3) // 1
val natural = shuffled.sorted() // 2
val inverted = shuffled.sortedBy { -it } // 3
println("Shuffled: $shuffled")
println("Natural order: $natural")
println("Inverted natural order: $inverted")
}
輸出結(jié)果:
Shuffled: [5, 4, 2, 1, 3]
Natural order: [1, 2, 3, 4, 5]
Inverted natural order: [5, 4, 3, 2, 1]
getOrElse
提供對集合元素的安全訪問鸵贬。它采用索引和函數(shù)俗他,在索引超出范圍時提供默認值。
fun main() {
val list = listOf(0, 10, 20)
println(list.getOrElse(1) { 42 }) // 1
println(list.getOrElse(10) { 42 }) // 2
}
輸出結(jié)果:
10
42
Map Element Access
應(yīng)用于map時阔逼,[]運算符返回與給定鍵對應(yīng)的值拯辙,如果map中沒有此類鍵,則返回null颜价。
getValue函數(shù)返回與給定鍵對應(yīng)的現(xiàn)有值,如果未找到該鍵則拋出異常诉濒。對于使用withDefault創(chuàng)建的映射周伦,getValue返回默認值而不是拋出異常。
fun main(args: Array<String>) {
val map = mapOf("key" to 42)
val value1 = map["key"] // 1
val value2 = map["key2"] // 2
val value3: Int = map.getValue("key") // 1
val mapWithDefault = map.withDefault { k -> k.length }
val value4 = mapWithDefault.getValue("key2") // 3
try {
map.getValue("anotherKey") // 4
}
catch (e: NoSuchElementException) {
println("Message: $e")
}
println("value1 is $value1")
println("value2 is $value2")
println("value3 is $value3")
println("value4 is $value4")
}
輸出結(jié)果:
Message: java.util.NoSuchElementException: Key anotherKey is missing in the map.
value1 is 42
value2 is null
value3 is 42
value4 is 4