컬렉션 유형
- list는 인덱스(위치를 반영하는 정수)로 요소에 액세스할 수 있는 정렬된 컬렉션입니다.
- set는 고유한 요소의 모음입니다.
- map은 키-값 쌍의 집합입니다. 키는 고유하며 각각은 정확히 하나의 값에 매핑됩니다. 값은 중복될 수 있습니다.
String 또는 사용자 정의 클래스로 수행하는 것과 동일한 방식으로 String 목록에 추가합니다. 따라서 Kotlin 표준 라이브러리는 모든 유형의 컬렉션을 만들고 채우고 관리하기 위한 일반 인터페이스, 클래스 및 함수를 제공합니다.StringInt
컬렉션 인터페이스 및 관련 기능은 kotlin.collections패키지에 있습니다. 그 내용을 대략적으로 살펴보자.
=> 제네릭에서 Any는 Object와 비슷한 개념임.
Kotlin Collection Functions Cheat Sheet
Enable learning and finding relevant collection function easier
medium.com
사용할 수 있는 사례를 유형 별로 정리되어 있음...
컬렉션 유형
Kotlin 표준 라이브러리는 세트, 목록 및 맵과 같은 기본 컬렉션 유형에 대한 구현을 제공합니다. 한 쌍의 인터페이스는 각 컬렉션 유형을 나타냅니다.
- 컬렉션 요소에 액세스하기 위한 작업을 제공 하는 읽기 전용 인터페이스입니다.
- 요소 추가, 제거 및 업데이트와 같은 쓰기 작업으로 해당 읽기 전용 인터페이스를 확장 하는 변경 가능한 인터페이스입니다.
변경 가능한 컬렉션을 변경하는 데 반드시 var 일 필요는 없습니다 . 쓰기 작업은 동일한 변경 가능한 컬렉션 개체를 수정하므로 참조가 변경되지 않습니다. 그러나 컬렉션을 재할당하려고 하면 val컴파일 오류가 발생합니다.
val numbers = mutableListOf("one", "two", "three", "four")
numbers.add("five") // this is OK
println(numbers)
//numbers = mutableListOf("six", "seven") // compilation error
읽기 전용 컬렉션 유형은 covariant 입니다. 즉, Rectangle클래스가 Shape에서 상속되는 경우 List가 필요한 모든 위치에서 사용할 수 있습니다 . 즉, 컬렉션 유형은 요소 유형과 동일한 하위 유형 지정 관계를 가집니다.
다음은 Kotlin 컬렉션 인터페이스의 다이어그램입니다.
인터페이스와 해당 구현을 살펴보겠습니다.
Collection
Collection<T> 컬렉션 계층 구조의 루트입니다. 이 인터페이스는 읽기 전용 컬렉션입니다. 다양한 컬렉션 유형에 적용되는 함수의 매개변수로 Iterable<T>사용할 수 있습니다 . Collection더 구체적인 경우에는 Collection의 상속자: List 및 Set.를 사용하십시오
fun printAll(strings: Collection<String>) {
for(s in strings) print("$s ")
println()
}
fun main() {
val stringList = listOf("one", "two", "one")
printAll(stringList)
val stringSet = setOf("one", "two", "three")
printAll(stringSet)
}
val numbers = listOf("one", "two", "three", "four")
println("Number of elements: ${numbers.size}")
println("Third element: ${numbers.get(2)}")
println("Fourth element: ${numbers[3]}")
println("Index of element \"two\" ${numbers.indexOf("two")}")
sample
fun List<String>.getShortWordsTo(shortWords: MutableList<String>, maxLength: Int) {
this.filterTo(shortWords) { it.length <= maxLength }
// throwing away the articles
val articles = setOf("a", "A", "an", "An", "the", "The")
shortWords -= articles
}
fun main() {
val words = "A long time ago in a galaxy far far away".split(" ")
val shortWords = mutableListOf<String>()
words.getShortWordsTo(shortWords, 3)
println(shortWords)
val stringList : List<String> = listOf("kin", "kwan", "yong", "logcenter")
val mixedTypeList : List<Any> = listOf("class", "object", 33, 24.5, "any the same")
for (value in mixedTypeList){
if (value is Int) {
println("value is int : multiple by 30 is ${value * 30}")
} else if (value is Double) {
println("value is double : ${value} and floor value ${floor(value)}")
} else if (value is String) {
println("value is string : ${value} and the length is ${value.length}")
} else {
println("value is nothing")
}
}
for(value in mixedTypeList){
when (value){
is Int -> {
println("value is int : multiple by 30 is ${value * 30}")
}
is Double -> println("value is double : ${value} and floor value ${floor(value)}")
is String ->
println("value is string : ${value} and the length is ${value.length}")
else -> println("value is nothing")
}
}
}
List<T>지정된 순서로 요소를 저장하고 요소에 대한 인덱스 액세스를 제공합니다.
val bob = Person("Bob", 31)
val people = listOf(Person("Adam", 20), bob, bob)
val people2 = listOf(Person("Adam", 20), Person("Bob", 31), bob)
println(people == people2)
bob.age = 32
println(people == people2)
val numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)
numbers.removeAt(1)
numbers[0] = 0
numbers.shuffle()
println(numbers)
보시다시피 어떤 측면에서 목록은 배열과 매우 유사합니다. 그러나 한 가지 중요한 차이점이 있습니다. 배열의 크기는 초기화 시 정의되며 절대 변경되지 않습니다. 차례로 목록에는 미리 정의된 크기가 없습니다. 목록의 크기는 요소 추가, 업데이트 또는 제거와 같은 쓰기 작업의 결과로 변경될 수 있습니다.
Kotlin에서 MutableList의 기본 구현은 조정 가능한 ArrayList 배열로 생각할 수 있습니다.
Sample Code
fun main() {
// val numbers: IntArray = intArrayOf(1,3,4,5,63,234,4)
// val numbers = intArrayOf(1,3,4,5,63,234,4) // type 추론
val numbers = arrayOf(1,3,4,5,6,2,4) // type 추론
println(numbers.contentToString())
println(numbers.sort())
val numbersDouble: DoubleArray = doubleArrayOf(32.3, 553.6, 29.9)
numbersDouble[0] = 2039.44
for (value in numbersDouble) {
println("${value%2} round is ${round(value/10)}")
}
val fruits = arrayOf(Fruit("Apple", 33.2), Fruit("Banana", 20.3))
println(fruits.contentToString())
println(fruits[0].name)
for (index in fruits.indices) {
println("${fruits[index].name} is in index : $index")
}
val mix = arrayOf("sun", "mon", 2,3,6, Fruit("Pear", 33.2))
println(mix.contentToString())
val month = arrayOf("January", "February", "March")
val mutableMonth = month.toMutableList()
val newMonths = arrayOf("April", "May", "June")
mutableMonth.addAll(newMonths)
mutableMonth.add("July")
println(mutableMonth)
val days = mutableListOf<String>("Saturday")
days.add("Mon"); days.add("Wed"); days.add("Sunday")
val removeList = listOf<String>("Mon")
days.removeAll(removeList)
println(days)
}
data class Fruit(val name: String, val price : Double)
Set
Set<T>고유한 요소를 저장합니다. 그들의 순서는 일반적으로 정의되지 않습니다. null요소도 고유합니다. 하나의 Set는 하나의 null 만 포함할 수 있습니다. 두 세트는 크기가 같고 세트의 각 요소에 대해 다른 세트에 동일한 요소가 있으면 동일합니다.
val numbers = setOf(1, 2, 3, 4)
println("Number of elements: ${numbers.size}")
if (numbers.contains(1)) println("1 is in the set")
val numbersBackwards = setOf(4, 3, 2, 1)
println("The sets are equal: ${numbers == numbersBackwards}")
MutableSet의 기본 구현은 LinkedHashSet으로 삽입 순서를 유지합니다. 따라서 first() 또는 last()와 같이 순서에 의존하는 함수는 이러한 집합에서 예측 가능한 결과를 반환합니다.
val numbers = setOf(1, 2, 3, 4) // LinkedHashSet is the default implementation
val numbersBackwards = setOf(4, 3, 2, 1)
println(numbers.first() == numbersBackwards.first())
println(numbers.first() == numbersBackwards.last())
Sample Code
val setList = setOf<String>("Orange", "Apple", "Grape", "Apple")
println(setList.size)
println(setList.toSortedSet())
val mutableFruits = setList.toMutableList()
mutableFruits.add("Mango")
mutableFruits.add("Water Melon")
println(mutableFruits.elementAt(3))
Map
Map<K, V>Collection인터페이스 의 상속자가 아닙니다 . 그러나 Kotlin 컬렉션 유형이기도 합니다. A Map는 키-값 쌍(또는 항목 )을 저장합니다. 키는 고유하지만 다른 키는 동일한 값과 쌍을 이룰 수 있습니다. 키로 값에 액세스, 키 및 값 검색 등과 같은 특정 기능을 제공합니다.
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
println("All keys: ${numbersMap.keys}")
println("All values: ${numbersMap.values}")
if ("key2" in numbersMap) println("Value by key \"key2\": ${numbersMap["key2"]}")
if (1 in numbersMap.values) println("The value 1 is in the map")
if (numbersMap.containsValue(1)) println("The value 1 is in the map") // same as previous
동일한 쌍을 포함하는 두 맵은 쌍 순서에 관계없이 동일합니다.
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
val anotherMap = mapOf("key2" to 2, "key1" to 1, "key4" to 1, "key3" to 3)
println("The maps are equal: ${numbersMap == anotherMap}")
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
numbersMap.put("three", 3)
numbersMap["one"] = 11
println(numbersMap)
MutableMap의 기본 구현은 LinkedHashMap맵으로 요소 삽입 순서를 유지합니다.
HashMap– 요소 순서 없음
Sample code for map
fun main() {
val daysMap = mapOf<Int, String>(1 to "Monday", 3 to "Tuesday", 2 to "Wednesday")
println("keys : ${daysMap.keys} and the values : ${daysMap.values}")
for(key in daysMap.keys)
print("$key is to ${daysMap[key]} , ")
println()
val fruitMap
= mapOf(
"Not Eat" to Fruit("Apple", 22.0),
"sometimes" to Fruit("Pear", 10.2),
"like" to Fruit("Peachy", 10.3))
println(fruitMap["sometimes"])
for(key in fruitMap.keys)
println("$key fruits is ${fruitMap[key]}")
println( daysMap.toSortedMap())
val mutableFruitMap = fruitMap.toMutableMap()
mutableFruitMap["most"] = Fruit("Banana", 3.0)
}
data class Fruit(val name: String, val price : Double)
사례
val myList = listOf<String>("kor", "usa", "france", "united kingdom","united kingdom kor sap india")
val myMutableList = mutableListOf(22, 44, 66, 3, 2, 1)
val mySet = setOf<String>("KO", "MZ", "AU", "EU")
val myMap = mapOf(3 to "three", 1 to "one", "up" to 2, "down" to 7, )
val empty = emptyList<String>()
val emptySet = emptySet<Int>()
val emptyMap = emptyMap<String, Int>()
fun main(){
val newList = myList.filter {
it.contains("o") || it == "usa" || it.length > 15
it.startsWith("f", ignoreCase = true)
}
println(newList)
println(myList.last())
print("$myMap")
print("\n ${myMap.entries}")
println()
println(myMap.values)
if(1 in myMap) println("YES key found") else println("no key founded")
if(7 in myMap.values) println("YES the value is in") else println("value is not in")
val myMutableMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
myMutableMap["four"] = 4
println(myMutableMap)
myList.forEach {
print("$it ") }
println()
myMutableList.add(3, 22)
myMutableList.forEach { print("$it, ") }
println()
myMutableList.removeAt(3)
myMutableList.remove(22)
myMutableList.forEach(System.out::print)
println()
println("index from value ${myList[3]}")
println("index of \"usa\" ${myList.indexOf("usa")+1}")
val myMutableSet = mutableSetOf(3, 45, 6, 8, 0)
myMutableSet.add(22)
myMutableSet.add(3)
}
collection은 filter를 사용해서 ... 여러 가지를 할 수 있음
'kotlin' 카테고리의 다른 글
kotlin Array (0) | 2023.02.07 |
---|---|
kotlin Cast - 형변환 (0) | 2023.02.07 |
kotlin OOB- inheretance (0) | 2023.02.07 |
kotlin Data classes (0) | 2023.02.06 |
kotlin OOB basic (0) | 2023.02.06 |