본문 바로가기

[Kotlin] Collection '컬렉션'

Kotlin - Collection '컬렉션'

 

Immutable(불변) / Mutable(가변)

  • 코틀린은 자바와 다르게 Collection을 2종류 타입으로 나눠서 구분 - Immutable / Mutable

    • Immutable (불변) 

         : Read-Only '읽기전용'의 Collection
           한번 정의되면 수정이 불가 - (add() / put() / remove() 등) 추가, 삭제 불가
           단순하게 추출하는 용도로 사용 

         : 생성 함수 (function)
           listOf, setOf, mapOf
    • Mutable (가변)

         : Write+Read '읽기/쓰기'의 Collection으로 add / put / remove 등이 가능

         : 생성 함수 (function)
           mutableListOf, mutableSetOf, mutableMapOf
           arrayListOf
           hashSetOf, sortedSetOf, linkedSetOf
           hashMapOf, linkedMapOf, sortedMapOf 

 

Collection에서의 Null 처리

  • 기본적으로 Nullable을 표기하기 위해선 Type뒤에 ?을 추가해서 Nullable을 가능하게 하였습니다
  • Collection에서는 Nullable을 위한 처리를 Collection객체 자체 or 원소에 붙일 수 있습니다   

    • List<Int> : list도 null이 아니고 원소도 null이 아님
    • List<Int?> : list는 null이 아니나 원소는 null이 가능 (nullable)
    • List<Int>? : list는 null이 될 수 있으나 원소는 null이 아님
    • List<Int?>? : list와 원소 모두 null이 가능
  • 위 예시들 처럼 Collection에서 Nullable을 위한 ?키워드는 위치에 따라 의미가 달라집니다

 

List

  • mutableListOf, arrayListOf 둘 다  ArrayList를 만들어서 리턴
  • ArrayList보다 Kotlin스타일로 리스트를 다루는 인터페이스가 구현되어 있는 MutableList를 사용이 더 나음
val list :List<Int> = listOf(1, 2, 3)			// Read-Only '읽기 전용'
val list :MutableList<Int> = mutableListOf(1, 2, 3)	// Write,Read '쓰기/읽기 가능'
val list :ArrayList<Int> = arrayListOf(1, 2, 3)		// Write,Read '쓰기/읽기 가능'
  • listOf()
    • 데이터가 일렬로 배열된 형태의 컬렉션
    • Immutable - 불변 'Read-Only'
    • Array와 유사한 형태
myList.sorted()  		// 알파벳순 정렬
myList[n]			// n번째 항목 반환
myList.first() 			// 처음 항목 반환
myList.last()	 		// 마지막 항목 반환
myList.contains(something)  	//something을 포함하는지 확인
  • ArrayList
    • listOf와 유사하지만 mutable 타입 - List의 수정 가능 
arrayList.add()			// 맨 끝에 항목 추가
arrayList.add(n,something)	// n번째에 항목 추가
arrayList.size() 		// List의 크기 반환
arrayList.indexOf(something) 	// something 항목의 번호를 반환(0부터 시작)
arrayList.remove(something)	// something을 삭제

 

Map

  • "key" to "value" (키값) 형태의 Data Collection
// new Instance - Map 생성함수
val map = mapOf("USA" to "워싱턴 D.C", "China" to "베이징", "Korea" to "서울") 		// Read-Only
val map = mutableMapOf("USA" to "워싱턴 D.C", "China" to "베이징", "Korea" to "서울") 	// Write,Read
val map = linkedMapOf("USA" to "워싱턴 D.C", "China" to "베이징", "Korea" to "서울")
val map = hashMapOf("USA" to "워싱턴 D.C", "China" to "베이징", "Korea" to "서울")
val map = sortedMapOf("USA" to "워싱턴 D.C", "China" to "베이징", "Korea" to "서울")

// Function in use
map.put("Japan", "도쿄")	// 추가(key, value), 동일 Key 없으므로 새로추가
map.put("Korea", "Seoul")	// 추가(key, value), 동일 Key 존재하므로 덮어쓰기
map.get("USA")			// 해당Key에 해당하는 value 반환
map["Korea"]			// get()과 동일
map.size			// Map크기 반환
map.containsKey("Korea")	// true, 해당 key 존재여부
map.containsKey("Australia") 	// false, 해당 key 존재여부
map.toList()			// map -> List 변환 (List value에 Map의 Pair객체로 변환 Pair(key=value))
map.toMutableMap()		// map -> mutableMap 변환
map.toSortedMap()		// map -> SortedMap 변환 (key를 기준으로 오름차순 정렬, 문자는 사전순)	
  • Map생성 함수를 보면 "key" to "value"에서 to키워드가 아닌 일반 함수입니다 (중간연산자)
  • For-Loop '컬렉션 순회'
val map = mapOf("Korea" to "서울", "USA" to "워싱턴 D.C", "Japan" to "도쿄")

for (item in map){		// item은 map의 pair 인스턴스 (Key=value 구조)
    println("$item")
}
// Korea=서울
// USA=워싱턴 D.C
// Japan=도쿄

for ((key, value) in map) {
    println("$item")
}
// 서울
// 워싱턴 D.C
// 도쿄

 

Set

  • TEXT
  • TEXT
// new Instance - Map 생성함수
val set = setOf("USA","Korea")      // ImmutableSet - 수정 불가
val set = mutableSetOf("USA","Korea")   // MutableSet
val set = hashSetOf("USA","Korea")
val set = linkedSetOf("USA","Korea")
val set = sortedSetOf("USA","Korea")

// Function in use
set.add("Japan")    // 추가, 중복 시 실패
set.remove("USA")   // 삭제
set.contains("USA")     // 해당 Element 존재여부
set.size    // 크기(사이즈)
set.toList()    // ImmutableList 변환
set.toMutableList() // MutableList 변환
set.toSet()
set.toMutableSet()
set.toSortedSet()   // 오름차순으로 정렬된 Set
set.toHashSet()

 

 

Ranges

// new Instance - Map 생성함수
for (i in 1..4) print(i)		// "1234" 출력
for (i in 1..4 step 2) print(i)		// "13" 출력, 2씩 증가
for (i in 4 downTo 1) print(i)		// "4321" 출력
for (i in 4 downTo 1 step 2) print(i)		// "31" 출력
(1..12 step 2).last // "11" 출력, last - 마지막요소(Element)