過濾與分組
filter
private fun filter() {
val mList = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
val resultList = mList.filter {
it > 5
}
println(resultList)
}
//[6, 7, 8, 9]
groupBy :
分組。即根據條件把集合拆分爲爲一個Map<K,List>類型的集合
private fun groupBy() {
val mList = arrayListOf(0, 1, 2, 3, 4, 5, 6)
val groupByList = mList.groupBy {
//定義key
it % 2 == 0
}
println(groupByList)
//這裏返回兩個元素的map
//{true=[0, 2, 4, 6], false=[1, 3, 5]}
groupByList.entries.forEach {
println("${it.key}==========${it.value}")
}
//true==========[0, 2, 4, 6]
//false==========[1, 3, 5]
}
private fun groupBy2() {
val mList = arrayListOf(0, 1, 2, 3, 4, 5, 6)
val groupByList = mList.groupBy {
//定義key
if (it % 2 == 0) {
"偶數"
} else {
"奇數"
}
}
println(groupByList)
//這裏返回兩個元素的map
//{偶數=[0, 2, 4, 6], 奇數=[1, 3, 5]}
groupByList.entries.forEach {
println("${it.key}==========${it.value}")
}
//偶數==========[0, 2, 4, 6]
//奇數==========[1, 3, 5]
}