Kotlin filter
役割:条件に合致した値のみリストに返却
使い方
filter
A.filter{ it XXXX }
→A(List)の1つ1つに対して順番に処理を実行し、XXXXの条件に合致するもののみリストに返却する
Stringのリストの各要素に対して処理実行
filter
fun filter(){
val okashiList = listOf("cookie","chocolate","pinapple","manjuu","chuppachapps")
println(okashiList.filter { it.contains("c") })
}
result
[cookie, chocolate, chuppachapps]
Integerのリストの各要素に対して処理実行
count
fun main(){
val pieList = listOf("3","1","4","1","5","9","2","6","5","3","5","8","9","7","9","3","2","3","8")
println(pieList.filter { it.toInt() % 2 == 0 })
println(pieList.filter { it.toInt() % 2 != 0 })
}
result
[4, 2, 6, 8, 2, 8]
[3, 1, 1, 5, 9, 5, 3, 5, 9, 7, 9, 3, 3]