인덱스로 원소에 접근 - Map 원소 접근시 괄호([]) 사용 코틀린에서는 맵의 원소에 접근할 때 자바에서 배열 원소에 접근하는 각 괄호([])를 사용할 수 있다. 인덱스 연산자는 get/set 관례를 따르며, Map과 MutableMap 인터페이스에는 이미 두 메서드가 들어가 있다. val value = map[key] mutableMap[key] = newValue 구현 예시 operator fun Point.get(index: Int): Int { return when(index) { 0 -> x 1 -> y else -> throw IndexOutOfBoundsException("Invalid coordinate $index") } } val p = Point(10, 20) println(p[1]..
collection
컬렉션 연산시 지연(lazy), 즉시(eagerly) 계산의 차이는 무엇인가? 즉시(eagerly)연산은 커렉션함수를 연쇄할 때마다 계산 중간 결과를 새로운 컬렉션에 임시로 담는다. 시퀀스(sequence)를 사용하면 중간 임시 컬렉션을 사용하지 않고 컬렉션 연산을 연쇄한다. people .filter { it.lastName != null } .filter { it. age!= null } .find { it.age == 31 } people.asSequence() // 컬렉션을 시퀀스로 변환 .filter { it.lastName != null } // Intermediate operation .filter { it. age!= null } // Intermediate operation .find {..
필수적인 함수: filter 와 map filter함수는 컬렉션을 이터레이션하면서 주어진 람다에 각 원소를 넘겨서 람다가 true를 반환하는 원소만 모은다. data class Person(val name: String, val age: Int) fun main() { val list = listOf(1, 2, 3, 4) println(list.filter { it%2 == 0 }) val people = listOf(Person("Alice", 29), Person("Bob", 31)) println(people.filter { it.age > 30 }) } filter 함수는 컬렉션에서 원치 않은 원소를 제거한다. 하지만 filter는 원소를 변환할 수는 없다. 원소를 변환하려면 map 함수를 사용해..
val set = hashSetOf(1, 7, 53) val list = arrayListOf(1, 7, 53) val map = hashMapOf(1 to "one", 7 to "seven", 53 to "fifty-three") // to는 특별한 키워드가 아니라 일반 함수이다. >> println(set.javaClss) // javaClass는 자바 getClass()와 같다 class java.util.HashSet >> println(list.javaClass) class java.util.ArrayList 코틀린 컬렉션은 자바 컬렉션과 똑같은 클래스다. 하지만 코틀린에서는 자바보다 더 많은 기능을 쓸 수 있다. >> var strings = listOf("first", "secord", "f..
동기화된 컬렉션(thread-safe한 collection), 병렬처리 컬렉션 컬렉션 프레임워크 대부분 싱글 스레드 환경에서 사용할 수 있도록 설계Vector, Hashtable은 동기화된 (synchronized) 메소드로 구성되어 있기 때문에 멀티 스레드 환경에서 안전함하지만 ArrayList, HashSet, HashMap 은 멀티스레드 환경에서 안전하지 않다. 따라서 자바에서는 Collections의 synchronizedXXX() 메소드를 제공한다.매개값으로 컬렉션을 대입하면 동기화된 컬렉션을 리턴한다. 리턴 타입메소드(매개변수)설명 ListsynchronizedList(List list)List를 동기화된 List로 리턴MapsynchronizedMap(Map m)Map을 동기화된 Map으로 ..