컬렉션의 요소를 반복하는 객체
(iterator is an object that loops through elements of a collection)
Iterator가 존재함으로 인해서 반복하는 요소를 인식할 수 있다.
순서가 지정된 컬렉션
// listOf를 통해 LIST를 생성한다. listOf를 통해 생성된 LIST는 Immutable하다.
val colors = listOf("blue","red","yellow")
// 빈 배열 생성의 경우 타입을 지정해준다.
val colors2 = listOf<String>()
// 중복 된 요소가 포함될 수 있다.
val colors3 = listOf("blue", "red", "blue", "green", "blue")
// null을 요소로 포함할 수 있다.(타입추론: <String?>)
val colors4 = listOf("blue","red","blue",null,null)
// index로 해당 요소를 검색할 수 있다.
println(colors[0]) // blue
// size로 해당 List의 요소의 개수를 알 수 있다.
println(colors4.size) // 5
// arrayListOf로 mutable한 list를 생성할 수 있다.
val colors5: ArrayList<String> = arrayListOf("blue","red")
// 빈 배열 생성의 경우 타입을 지정해준다.
val noColors = arrayListOf<String>()
// 요소 추가 메서드
colors5.add("yellow")
val moreColors = arrayListOf("pink","teal")
// 다른 배열을 참조하여 해당 배열에 추가할 수 있다.
colors5.addAll(moreColors) // [blue,red,yellow,pink,teal]
// 배열 내 요소를 제거할 수 있다.
colors5.remove("red") // [blue,yellow,pink,teal]
// 다른 배열을 참조하여 삭제할 수 있다.
colors5.removeAll(moreColors) // [blue,yellow]
// index로 배열 내 요소를 삭제할 수 있다.
colors5.removeAt(1) // [blue]
colors5.add("red")
colors5.add("blue")
// remove로 배열 내 요소를 삭제할 시 요소 전체가 아닌 조건에 부합하는 하나의 요소만 삭제된다.
colors5.remove("blue") // [red,blue]
연습
val customers = arrayListOf("tom","emerson","judy","jade","darrick")
println("Add or Delete")
val addOrDelete = readLine();
if(addOrDelete == "add"){
println("add to user")
val user = readLine()
customers.add(user!!)
}
if(addOrDelete == "delete"){
println("delete to user")
val user = readLine()
customers.remove(user!!)
}
println(customers)
val items = arrayListOf("laptop", "mouse", "pen", "paper", "mug", "phone")
val removedItems = listOf("pen", "paper", "mug", "phone")
items.removeAll(removedItems) // [laptop,mouse]
val customers = arrayListOf("tom","emerson","judy","jade","darrick")
customers.contains("red") // false
customers.containsAll(listOf("judy","darrick")) // true
customers.containsAll(listOf("judy","red")) // false
customers.indexOf("emerson") // 1
customers.add("tom")
customers.lastIndexOf("tom") // 5
customers.indexOf("tom") // 0
// 특정 인덱스에 특정 요소를 배치하려면 set 함수를 사용할 수 있다.
customers.set(3,"evelyn")
// kotlin은 indexing을 통한 배치를 선호하기에 아래와 같이 바꿀 수 있다.
customers[3] = "evelyn"
val customers = arrayListOf("tom","emerson","judy","jade","darrick")
val subCustomers = customers.subList(1,4) // [emerson,judy,jade]
customers.isEmpty() // false
customers.clear() // []
customers.isEmpty() // true
val customers = arrayListOf("tom","emerson","judy","jade","darrick")
customers[customers.indexOf("judy")] = "brick"
customers // [tom,emerson,brick,jade,darrick]
val animals = arrayListOf("lion", "zebra", "chimp", "elephant")
animals.add("panda")
animals.remove("lion")
println("is there elephant and giraffe ? ${animals.containsAll(listOf("elephant","giraffe"))}") // false
println("is there elephant and panda ? ${animals.containsAll(listOf("elephant","panda"))}") // true
Group of unique elements
고유한 요소를 정의되지 않은 순서로 저장하는 컬렉션
각 요소가 고유(Unique)하다는 것은 중복되지 않다는 것을 뜻한다.
// 중복되는 6은 제거된다.
val numbers = setOf(6,32,55,6,47) // [6,32,55,47]
// 빈 집합을 생성할 수 있으며 이 경우 타입을 지정해야 한다.
val noElementsSet = setOf<Int>() // []
// nullable한 set을 생성할 수 있다.
val nullableSet = setOf(3,4,8,null,55,null,596L,null) // [3,4,8,null,55,596]
// set은 Immutable하므로 mutable한 set으로 hashSet을 사용할 수 있다.
val hashSet = hashSetOf(3,4,55,null,5,64,64) // [null,64,3,4,5,55]
hashSet.add(3334) // [null,64,3,4,5,3334,55] - 순서를 보장하지 않음을 유의.
// addAll,removeAll은 collection을 인수로 받아 추가하거나 제거할 수 있다.
hashSet.addAll(listOf(3,10,14,17)) // [null,64,17,3,4,5,3334,55,10,14]
hashSet.addAll(setOf(99,100)) // [null, 64, 17, 3, 99, 4, 100, 5, 3334, 55, 10, 14]
hashSet.remove(3334) // [null, 64, 17, 3, 99, 4, 100, 5, 55, 10, 14]
hashSet.removeAll(listOf(null,64,17,3,4,5)) // [99, 100, 55, 10, 14]
//removeAll에서 인수로 사용하는 collection의 요소 중 hashSet에 없는 요소는 무시한다. (Exception 되지 않음에 유의)
hashSet.removeAll(setOf(100,41432,445553)) // [99, 55, 10, 14]
연습
val stacks = hashSetOf("Java","Kotlin","React","JavaScript","ReactNative")
stacks.size // 5
stacks.contains("React") // true
stacks.contains("Python") // false
stacks.containsAll(setOf("Kotlin","Java")) // true
stacks.containsAll(setOf("ReactNative, HTML")) // false
stacks.isNotEmpty() // true
stacks.clear() // []
stacks.isEmpty() // true
val myStacks = hashSetOf("Kotlin","React","JavaScript","ReactNative")
val yourStacks = setOf("PHP","Nest","Python","React")
// retainAll은 타겟을 교집합으로 변경하므로 일반 set에서는 사용할 수 없다.
myStacks.retainAll(yourStacks)
println(myStacks) // [React]
기본적으로 컬렉션은 아니다.
MAP 또한 순서를 보장하지 않는다.
key와 value의 pair로 이루어 지며 key는 set이므로 고유하다.
다른 key에 value는 같을 수 있다.
// Pair(key,value)로 요소를 정의하며, key to value 형식으로도 정의가 가능하다.
val count = hashMapOf(Pair(1,"one"), Pair(2,"two"), Pair(3,"three"))
val count2 = mapOf(4 to "four", 5 to "five", 6 to "six")
count.putAll(count2) // {1=one, 2=two, 3=three, 4=four, 5=five, 6=six}
// put 대신 indexing을 사용하는 것을 권장한다.
count[7] = "seven"
// key를 인수로 제공하여 요소를 삭제할 수 있다.
println(count.remove(5)) // five
println(count) // {1=one, 2=two, 3=three, 4=four, 6=six, 7=seven}
count.replace(6, "여섯")
println(count) // {1=one, 2=two, 3=three, 4=four, 6=여섯, 7=seven}
count.clear()
println(count) // {}
연습
val count = hashMapOf(Pair(1,"one"), Pair(2,"two"), Pair(3,"three"))
println("this hashMap size is ${count.size}") // 3
println("does count has key 2 ? ${count.containsKey(2)}") // true
println("does count has value \"four\" ? ${count.containsValue("four")}") // false
val attendance = hashMapOf(Pair("23 Sept", 2837), Pair("24 Sept", 3726), Pair("25 Sept", 6253))
attendance["26 Sept"] = 9901
val total = attendance["25 Sept"]!!.toInt() + attendance["26 Sept"]!!.toInt()
println(total) // 16154
println(attendance.containsKey("22 Sept")) // false