[kotlin] 코틀린 집합(Set)에 원소 추가하기

코틀린에는 변경 가능한 mutableSetOf과 변경 불가능한 setOf 두 가지 유형의 집합이 있습니다. 일단 집합을 생성한 후에는 .add() 메서드를 사용하여 원소를 추가할 수 있습니다.

예를 들어, 다음은 변경 가능한 집합에 원소를 추가하는 방법입니다.

val mutableSet = mutableSetOf("apple", "banana", "orange")
mutableSet.add("grape")

또는 변경 불가능한 집합에 원소를 추가하는 방법은 다음과 같습니다.

val immutableSet = setOf("apple", "banana", "orange")
val extendedSet = immutableSet.plus("grape")

위의 예에서 plus 함수는 새로운 집합을 반환하며, 원래 집합을 변경하지 않습니다.

집합에 있는 원소를 변경하거나 수정하는 방법은 다음과 같습니다.집합에 있는 원소를 변경하거나 수정하는 방법은 다음과 같습니다.

val mutableSet = mutableSetOf("apple", "banana", "orange")
mutableSet.remove("banana")
mutableSet.clear()

집합의 참조를 유지하면서 새로운 원소를 추가하거나 기존 원소를 제거할 수 있습니다.

이렇게하면 원하는 집합을 손쉽게 수정하고 관리할 수 있습니다.

References

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/set-of.html