List<String>
์์์ ํํฐ ์ฌ์ฉval answer1 = languageList.filter {
it == "C"
}
println("filter: $answer1")
>> filter: [C]
val answer2 = languageList.filterNot {
it == "C"
}
println("filterNot: $answer2")
>> filterNot: [Python, R, Kotlin, C++]
val languageList = listOf("Python", "R", "Kotlin", "C++", "C")
val startAnswer = languageList.filter {
it.startsWith("C")
}
println("startsWith: $startAnswer")
>> startsWith: [C++, C]
val languageList = listOf("Python", "R", "Kotlin", "C++", "C")
val endAnswer = languageList.filter {
it.endsWith("n")
}
println("endsWith: $endAnswer")
>> endsWith: [Python, Kotlin]
val answer3 = languageList.filterIndexed { index, s ->
index == 3
}
println("filterIndexed: $answer3")
>> filterIndexed: [C++]
๋ฆฌ์คํธ์ null์ด ํฌํจ๋์ด ์์ ๊ฒฝ์ฐ์๋ Notnull String์์ ์ฌ์ฉํ ์ ์๋ ํจ์๋ฅผ ์ฌ์ฉํ์ ๋ ์ปดํ์ผ์ด ๋์ง ์๋๋ค.
val nullContainList = listOf(null, "Python", "R", "Kotlin", "C++", "C")
println(nullContainList)
println(nullContainList.filterNotNull())
val answer4 = nullContainList.filterNotNull().filter {
it.startsWith("C")
}
println("filterNotNull: $answer4")
[null, Python, R, Kotlin, C++, C]
[Python, R, Kotlin, C++, C]
filterNotNull: [C++, C]
val anyList = listOf(null, 150, 100, "Python", "R", "Kotlin", "C++", "C")
๋ฆฌ์คํธ์ null๊ณผ Int๊ฐ ํฌํจ๋์ด ์๊ธฐ ๋๋ฌธ์ String์์ ๊ฐ์ ๋น๊ตํ๊ณ ์ถ์ ๋๋ if(it is String)
๊ณผ ๊ฐ์ if๋ฌธ์ ๊ฑฐ์ณ์ผ ํ๋ค
๋งค๋ฒ ํ์
์ฒดํฌ๋ฅผ ํ๋ ๊ฒ์ ๋ฒ๊ฑฐ๋ก์ฐ๋ ํํฐ๋ก ๊ฑธ๋ฌ์ฃผ์.
val answer5 = anyList.filterIsInstance<String>().filter{
it.startsWith("C")
}
println("filterIsInstance<String>: $answer5")
val answer6 = anyList.filterIsInstance<Int>().filter{
it == 100
}
println("filterIsInstance<Int>: $answer6")
filterIsInstance<String>: [C++, C]
filterIsInstance<Int>: [100]