[Kotlin] Collection : list, set, map

2021. 5. 25. 13:43

Immutable Collections : ๋ณ€๊ฒฝ ๋ถˆ๊ฐ€๋Šฅ

list : ์ค‘๋ณต ํ—ˆ์šฉ, ์ธ๋ฑ์Šค๋กœ ์ ‘๊ทผ

val numberList = listOf<Int>(1, 2, 3, 3)
numberList.get(0)
numberList[0]

 

set : ์ค‘๋ณต ํ—ˆ์šฉํ•˜์ง€ ์•Š์Œ, ์ˆœ์„œ๊ฐ€ ์—†์Œ

val numberSet = setOf<Int>(1, 2, 3, 3)

 

map : key, value ๋ฐฉ์‹์œผ๋กœ ๊ด€๋ฆฌ, ์ธ๋ฑ์Šค์—†์ด key๋กœ ๊ฒ€์ƒ‰

val numberMap = mapOf<String, Int>("one" to 1, "two" to 2)
numberMap.get("one")

 

Mutable Collections : ๋ณ€๊ฒฝ ๊ฐ€๋Šฅ

list

: .add(์ธ๋ฑ์Šค, ๊ฐ’) ํ˜•ํƒœ๋กœ ํ•ด๋‹น ์ธ๋ฑ์Šค ์ž๋ฆฌ์— ์ถ”๊ฐ€ ๊ฐ€๋Šฅ, .add(๊ฐ’) ํ˜•ํƒœ๋กœ๋„ ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค์— ์ถ”๊ฐ€ ๊ฐ€๋Šฅ

 .set(์ธ๋ฑ์Šค, ๊ฐ’) ํ˜•ํƒœ๋กœ ํ•ด๋‹น ์ธ๋ฑ์Šค ๊ฐ’ ๋ณ€๊ฒฝ ๊ฐ€๋Šฅ

 .removeAt(์ธ๋ฑ์Šค) ํ˜•ํƒœ๋กœ ํ•ด๋‹น ์ธ๋ฑ์Šค ๊ฐ’ ์‚ญ์ œ

val mNumberList = mutableListOf<Int>(1, 2, 3)
mNumberList.add(3, 4)
mNumberList.set(0, 10)
mNumberList.removeAt(0)

 

set

: .add(๊ฐ’) ํ˜•ํƒœ๋กœ ์ถ”๊ฐ€ ๊ฐ€๋Šฅ, ์ธ๋ฑ์Šค๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์— ์ธ์ž ํ•˜๋‚˜๋งŒ ๋ฐ›์Œ

 .remove(๊ฐ’) ํ˜•ํƒœ๋กœ ํ•ด๋‹น ๊ฐ’์ด ์žˆ์œผ๋ฉด ์‚ญ์ œ, ์—†์œผ๋ฉด ์—๋Ÿฌ ๋ฐœ์ƒํ•˜์ง€ ์•Š๊ณ  ์•„๋ฌด์ผ๋„ ์ผ์–ด๋‚˜์ง€์•Š์Œ

val mNumberSet = mutableSetOf<Int>(1, 2, 3, 3)
mNumberSet.add(4)
mNumberSet.remove(1)

 

map

: .put(key, value) ํ˜•ํƒœ๋กœ ์ถ”๊ฐ€ ๊ฐ€๋Šฅ

 .replace(key, value) ํ˜•ํƒœ๋กœ key์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ’ ๋ณ€๊ฒฝ

 .keys ํ˜•ํƒœ๋กœ key๋งŒ ์ถœ๋ ฅ

 .values ํ˜•ํƒœ๋กœ value๋งŒ ์ถœ๋ ฅ

 .clear() ํ˜•ํƒœ๋กœ ๋ชจ๋“  ๊ฐ’ ์‚ญ์ œ

val mNumberMap = mutableMapOf<String, Int>("one" to 1, "two" to 2)
mNumberMap.put("three" to 3)
mNumberMap.replace("three" to 30)
println(mNumberMap.keys)
println(mNumberMap.values)
mNumberMap.clear()
728x90

BELATED ARTICLES

more