๐Ÿ”ฅTIL๐Ÿ”ฅ์ŠคํŒŒ๋ฅดํƒ€ | ์ฝ”ํ‹€๋ฆฐ ํ™•์žฅํ•จ์ˆ˜ map

hyihyiยท2023๋…„ 11์›” 30์ผ
0

TIL

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

filter, map : ๋ฆฌ์ŠคํŠธ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•จ

์ •์ˆ˜ ๋ฆฌ์ŠคํŠธ ๊ฐ ์š”์†Œ๋ฅผ ์ œ๊ณฑํ•˜๋Š” ์˜ˆ์‹œ

val numbers = listOf(1, 2, 3, 4, 5)
val squaredNumbers = numbers.map { it * it }
println(squaredNumbers)
[1, 4, 9, 16, 25]

๋ฌธ์ž์—ด ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด๋ฅผ ๊ตฌํ•˜๋Š” ์˜ˆ์‹œ

val strings = listOf("apple", "banana", "cherry")
val lengths = strings.map { it.length }
println(lengths)
[5, 6, 6]

์‚ฌ์šฉ์ž ์ •์˜ ํด๋ž˜์Šค์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋‹ค๋ฅธ ์†์„ฑ์œผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ์˜ˆ์‹œ

data class Person(val name: String, val age: Int)
val people = listOf(Person("Alice", 25), Person("Bob", 30), Person("Charlie", 22))
val name = people.map { it.name }
println(people)
println(name)
[Person(name=Alice, age=25), Person(name=Bob, age=30), Person(name=Charlie, age=22)]
[Alice, Bob, Charlie]

์ปฌ๋ ‰์…˜์˜ ๊ฐ ์š”์†Œ๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ์˜ˆ์‹œ

val intNumbers = listOf(1, 2, 3, 4, 5)
val stringNumbers = intNumbers.map { it.toString() }
println(stringNumbers)
[1, 2, 3, 4, 5]

๋„์‹œ ์ด๋ฆ„์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์ €์žฅ ํ›„ ์ถœ๋ ฅ

val cities = listOf("Seoul", "Tokyo", "New york")

	//1
  	cities.map{
     	println(it.toUpperCase())
  	}

	//2
    cities.map{city->city.toUpperCase()}
        .forEach{println(it)}
SEOUL
TOKYO
NEW YORK
SEOUL
TOKYO
NEW YORK

๋„์‹œ ์ด๋ฆ„์„ ๊ธธ์ด๋กœ ๋ณ€ํ™”ํ•˜์—ฌ ์ €์žฅ ํ›„ ์ถœ๋ ฅ

val cities = listOf("Seoul", "Tokyo", "New york")

    //1
    cities.map{
        println(it.length)
    }
    
    //2
    cities.map{ city -> city.length }
        .forEach{ println("LENGTH:$it")}

mapNotnull()์€ ์ปฌ๋ ‰์…˜ ๋‚ด ๊ฐ ์š”์†Œ๋ฅผ ๋ณ€ํ™˜ํ•จ๊ณผ ๋™์‹œ์— ์š”์†Œ๊ฐ€ null์ธ ๊ฒฝ์šฐ ๋ฌด์‹œํ•œ๋‹ค.

cities.mapNotNull { city -> if(city.length < 6) city else null }
    .forEach{ println(it) }
}
5
5
8
LENGTH:5
LENGTH:5
LENGTH:8
Seoul
Tokyo
profile
๋‚ด๊ฐ€ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์“ฐ๋Š” ๋ธ”๋กœ๊ทธ

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