直接看代码
fun main(){
val numberList1 = listOf(23, 65, 14, 57, 99, 123, 26, 15, 88, 37, 56)
val numberList2 = listOf(13, 55, 24, 67, 93, 137, 216, 115, 828, 317, 16)
val numberList3 = listOf(20, 45, 19, 7, 9, 3, 26, 5, 38, 75, 46)
val oddNumberList = mutableListOf<Int>()
numberList1.filterTo(oddNumberList) {
it % 2 == 1
}
numberList2.filterTo(oddNumberList) {
it % 2 == 1
}
numberList3.filterTo(oddNumberList) {
it % 2 == 1
}
//需要注意一点的是,我们从源码看到filterTo第一个参数destination是一个可变集合类型,所以这里使用的mutableListOf初始化
val evenNumberList = mutableListOf<Int>().apply {
numberList1.filterTo(this) {
it % 2 == 0
}
numberList2.filterTo(this) {
it % 2 == 0
}
numberList3.filterTo(this) {
it % 2 == 0
}
}
print("从三个集合筛选出的奇数集合: \n")
oddNumberList.forEach {
print("$it ")
}
println("\n")
print("从三个集合筛选出的偶数集合: \n")
evenNumberList.forEach {
print("$it ")
}
println("\n")
}