๐Ÿ”ฅTIL๐Ÿ”ฅ์ŠคํŒŒ๋ฅดํƒ€ | filter

hyihyiยท2023๋…„ 12์›” 6์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
13/70
post-thumbnail

Collections์—์„œ ์“ธ ์ˆ˜ ์žˆ๋Š” Filter ํ•จ์ˆ˜

List<String> ์—์„œ์˜ ํ•„ํ„ฐ ์‚ฌ์šฉ

filter : ํŠน์ • ์กฐ๊ฑด์— ๋ถ€ํ•ฉํ•  ๋•Œ

val answer1 = languageList.filter {
    it == "C"
}
println("filter: $answer1")
>> filter: [C]

filterNot : ํŠน์ • ์กฐ๊ฑด์ด ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋‚จ๊ธฐ๊ณ  ์‹ถ์„ ๋•Œ

val answer2 = languageList.filterNot {
    it == "C"
}
println("filterNot: $answer2")
>> filterNot: [Python, R, Kotlin, C++]

startsWith("๋ฌธ์ž") : ํŠน์ • ๋ฌธ์ž๋กœ ์‹œ์ž‘ํ•˜๋Š”์ง€ ํ™•์ธ

val languageList = listOf("Python", "R", "Kotlin", "C++", "C")
val startAnswer = languageList.filter {
    it.startsWith("C")
}
println("startsWith: $startAnswer")
>> startsWith: [C++, C]

endsWith("๋ฌธ์ž") : ํŠน์ • ๋ฌธ์ž๋กœ ๋๋‚˜๋Š”์ง€ ํ™•์ธ

val languageList = listOf("Python", "R", "Kotlin", "C++", "C")
val endAnswer = languageList.filter {
    it.endsWith("n")
}
println("endsWith: $endAnswer")
>> endsWith: [Python, Kotlin]

filterIndexed : ์ธ๋ฑ์Šค์™€ ๊ฐ’์„ ๊ฐ๊ฐ ๋ฐ›๊ณ  ์‹ถ์„ ๋•Œ

val answer3 =  languageList.filterIndexed { index, s ->
    index == 3
}
println("filterIndexed: $answer3")
>> filterIndexed: [C++]

๋งŒ์•ฝ ๋ฆฌ์ŠคํŠธ์— null์ด ํฌํ•จ๋˜์–ด ์žˆ๋‹ค๋ฉด??

filterNotNull : null๊ฐ’์„ ์ œ์™ธํ•œ list๋ฅผ ๋ฐ˜ํ™˜๋ฐ›๋Š”๋‹ค.

๋ฆฌ์ŠคํŠธ์— 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]

filterIsInstance : ์›ํ•˜๋Š” ์ž๋ฃŒํ˜•์—์„œ์˜ filter๋ฅผ ํ•˜๊ณ  ์‹ถ์„ ๋•Œ

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]
profile
๋‚ด๊ฐ€ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์“ฐ๋Š” ๋ธ”๋กœ๊ทธ

0๊ฐœ์˜ ๋Œ“๊ธ€