20. List
▷ List<out T> : 생성시에 넣은 객체를 대체, 추가, 삭제 할 수 없음
▷ MutableList<T> : 생성시에 넣은 객체를 대체, 추가, 삭제 가능
▷ 리스트 생성
· listOf(1,3,4)
· mutableListOf(“A”,”B”, “d”)
- 추가 : add(데이터) 또는 add(인덱스, 데이터)
- 삭제 : remove(데이터) 또는 removeAt(인덱스)
▷ 무작위 섞기 : shuffle()
▷ 정렬 : sort()
▷ list[인덱스] = 데이터
fun main() {
var a = listOf("apple", "strawberry", "pear")
for (i in a) { print("${i} : ") }
var b = mutableListOf(4, 7, 8, 9, 33)
b.add(88)
b.remove(7)
println(b)
b.removeAt(1)
b.add(3, 3)
println(b)
b.sort()
println(b)
b.shuffle()
println(b)
}
21. List-Set과 Map
▷ 코틀린이 기본적으로 지원하는 컬렉션 class Set, Map
▷ class Collection à class List, class Set, class Map 이 있음
set
▷ 중복이 허용되지 않는 collection
▷ 인덱스로 위치를 지정해서 객체를 참조할 수 없음
▷ samSet.contains(“다무”) 처럼 확인하는 식으로만 사용함
▷ Set<out T> MutableSet<T> à add(), remove()
fun main () {
val a = mutableSetOf("orange", "banana", "Kiwi")
for (item in a) { println("${item}") }
a.add("apple")
a.remove("banana")
println(a)
println(a.contains("orange"))
}
map
▷ 객체를 넣어 줄 때 key 값을 같이 넣어 주는 collection
▷ key : 주소, value : 값
▷ Map<K, out V> MutableMap<K, V> à put(key, value), remove(key)
fun main () {
val a = mutableMapOf("call" to "12digits",
"name" to "myName",
"gender" to "male")
for ( info in a) {
println("${info.key} : ${info.value}")
}
a.put("age", "55")
a.remove("call")
println(a)
println(a["age"])
}
22. list, dictionary
함수-1
▷ collection에 대해 일반함수나 람다 함수 형태를 사용해서 for, if 같은 기능을 수행
collection.forEach{ print(it) }
collection.filter { it < 4 }
collection.map { it * 2 }
collection.any{ it == 0 }
collection.all{ it == 0 }
collection.none{ it == 0 }
collection.first{ it > 3 } // 조건에 맞으면 값 반환 à find
collection.last{ it < 3 } // à findLast
// 값이 null 이면 문제 발생
collection.firstOrNull{} // 객체가 없으면 null
collection.lastOrNull{}
collection.count{ it > 5 } // 개수를 반환
fun main () {
val a = listOf("me", "you", "we", "ours", "yours")
a.forEach{ print(it + " - ") }
println(a.filter{ it.startsWith("w")})
println(a.map{ it + " together"})
println(a.any{ it == "us" })
println(a.all{ it.length == 3})
println(a.any{ it.length == 3})
println(a.none{ it == "me"})
println(a.first{ it.startsWith("y")})
println(a.last{ it.endsWith("e")})
println(a.count{ it.length > 3 })
println(a.count{ it.contains("o")})
}
함수-2
collection.associateBy { it.name }
collection.groupBy { it.birthYear }
collection.partition { it.birthYear > 2002 }
fun main () {
data class P(val name : String, val birth : Int)
val PList = listOf(P("me", 1967),
P("you", 1970),
P("son", 2003),
P("son", 2001),
P("daughter", 2005))
println(PList.associateBy{it.birth})
println(PList.groupBy{ it.name})
val (over2000, under2000) = PList.partition{ it.birth > 2000 }
println(over2000)
println(under2000)
}
//아이템마다 만들어진 컬렉션을 합쳐서 반환
collection.flatMap{ listOf(it*3, it+3) }
fun main () {
val lint = listOf(1,3, 5)
println(lint.flatMap{ listOf(it*3, it+3, it*10) })
}
// 인덱스 위치에 아이템이 있으면 아이템을 반환하고 아닌 경우 지정한 기본값을 반환
collection.getOrElse() { }
var lst = listOf(4,6,7,9,3)
lst.getOrElse(20) { 30 } /20의 위치(index)에 값이 없으므로 30을 반환
// 컬렉션 2개의 아이템을 1:1로 매칭하여 새 컬렉션을 만듦, 아이템 수는 더 작은 것을 따라감
collectionA zip collectionB
var lst1 = listOf(1,2,3,6)
var lst2 = listOf(A, B, C, D)
println(lst1 zip lst2)
'kotlin' 카테고리의 다른 글
Kotlin null 처리 (0) | 2023.01.14 |
---|---|
Kotlin String (0) | 2023.01.14 |
Kotlin class-03; Object, companion object, Generic (0) | 2023.01.14 |
Kotlin class-02 (0) | 2023.01.14 |
Kotlin class-01 (0) | 2023.01.14 |