过滤与分组
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]
}