개발 일기

Collection Write Operations 본문

컴퓨터 언어/kotlin

Collection Write Operations

이건욱

Mutable Collection에서 데이터를 추가하거나 삭제하는 방법에 대해서 설명을 하도록 하겠습니다.

데이터 추가

먼저 제일 기본적으로 하나의 데이터를 추가하는 방법입니다.

아래와 같이 "add" 함수를 통해서 진행을 할수가 있습니다.

val numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)
println(numbers)

[1, 2, 3, 4, 5]

 

다음으로 list or set을 추가하고 싶은 경우에는 "addAll"을 사용할수가 있습니다.

val numbers = mutableListOf(1, 2, 5, 6)
numbers.addAll(arrayOf(7, 8))
println(numbers)
numbers.addAll(2, setOf(3, 4))
println(numbers)

[1, 2, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

마지막으로 plus operator - plusAssign(+=) 을 통해서도 추가할수가 있습니다.

val numbers = mutableListOf("one", "two")
numbers += "three"
println(numbers)
numbers += listOf("four", "five")    
println(numbers)

[one, two, three]
[one, two, three, four, five]

 

데이터 삭제

하나를 삭제하고 싶은경우에는 remove() 함수를 통해서 삭제할수가 있습니다.

val numbers = mutableListOf(1, 2, 3, 4, 3)
numbers.remove(3)                    // removes the first `3`
println(numbers)
numbers.remove(5)                    // removes nothing
println(numbers)

[1, 2, 4, 3]
[1, 2, 4, 3]

 

하나 이상의 값을 삭제하고 싶은 경우에는 "removeAll" or "retainAll" or "clear" 통해서 삭제할수가 있습니다.

val numbers = mutableListOf(1, 2, 3, 4)
println(numbers)
numbers.retainAll { it >= 3 }
println(numbers)
numbers.clear()
println(numbers)
val numbersSet = mutableSetOf("one", "two", "three", "four")
numbersSet.removeAll(setOf("one", "two"))
println(numbersSet)

[1, 2, 3, 4]
[3, 4]
[]
[three, four]

 

여기에서도 마찬가지로 minusAssign(-=)이 존재합니다. 

val numbers = mutableListOf("one", "two", "three", "three", "four")
numbers -= "three"
println(numbers)
numbers -= listOf("four", "five")    
//numbers -= listOf("four")    // does the same as above
println(numbers)    

[one, two, three, four]
[one, two, three]

'컴퓨터 언어 > kotlin' 카테고리의 다른 글

Set Specific Operations  (0) 2020.06.08
List Specific Operations  (0) 2020.06.05
Collection Aggregate Operations  (0) 2020.06.02
Collection 순서 정렬  (0) 2020.06.01
List or Set에서 데이터 검색  (0) 2020.05.29
Comments