Programming/Kotlin

[Kotlin] object list μ—μ„œ νŠΉμ • ν•„λ“œ κ°’ (field value) κ°€μ Έμ˜€λŠ” 방법

yuri lee 2023. 1. 7. 16:19
λ°˜μ‘ν˜•

Intro 

μ•ˆλ…•ν•˜μ„Έμš”. 이번 μ‹œκ°„μ—λŠ” object listμ—μ„œ 단일 field 값을 κ°€μ Έμ˜€λŠ” 방법에 λŒ€ν•΄ μ•Œμ•„λ³΄λ„λ‘ ν•˜κ² μŠ΅λ‹ˆλ‹€. μ˜ˆλ₯Ό λ“€μ–΄ μ•„λž˜μ™€ 같은 μ½”ν‹€λ¦° μ½”λ“œκ°€ μžˆλ‹€κ³  κ°€μ •ν•΄λ΄…μ‹œλ‹€. μ—¬κΈ°μ„œ { "hong", "kil" } 와 같은 ν˜•μ‹μœΌλ‘œ 단일 ν•„λ“œ κ°’λ§Œ κ°€μ Έμ˜€κ³  μ‹ΆμœΌλ©΄ μ–΄λ–»κ²Œ ν•΄μ•Ό ν• κΉŒμš”? 

fun main(args:Array<String>){
    println("Hello World")
    val list = listOf(member("hong",10), member("kil", 10))
}

data class member(var name:String, var age:Int)

 

How to solve the problem

μ•„λž˜μ™€ 같이 κ°„λ‹¨ν•˜κ²Œ map() λ©”μ†Œλ“œλ₯Ό ν†΅ν•˜μ—¬ nameμ΄λΌλŠ” ν•„λ“œλ§Œ κ°€μ Έμ˜¬ 수 μžˆμŠ΅λ‹ˆλ‹€. 

val names = list.map { it.name }

 

 


https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map.html

https://stackoverflow.com/questions/50603424/how-to-get-single-field-value-in-object-list

λ°˜μ‘ν˜•