Map
- Item들을 특정 함수를 활용하여 변형 시키고, 그 결과값에 대한 Collection을 반환 해 줌
map() / mapIndexed()/ mapNotNull() 등의 operation이 존재
fun checkDefaultMapOperator() {
val numbers = setOf(1, 2, 3)
println(numbers.map { it * 3 })
println(numbers.mapIndexed { idx, value -> value * idx })
val numbersNullCheck = setOf(1, 2, 3)
println(numbersNullCheck.mapNotNull { if ( it == 2) null else it * 3 })
println(numbersNullCheck.mapIndexedNotNull { idx, value -> if (idx == 0) null else value * idx })
}
- map collection을 변형 시킬 때는, value는 놔둔 채 key를 변형시키는
mapKey(), 그와 반대로 작동하는 mapValues() 가 존재
fun makeMapCollectionUsingMapOperator() {
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
println(numbersMap.mapKeys { it.key.toUpperCase() })
println(numbersMap.mapValues { it.value + it.key.length })
}
Zip
- 각각 Collection의 동일한 position에 있는 item들을 결합 ( Pair의 형태 ) 하여 새로운 Collection을 반환
- collection과 collection을 zip으로 엮으면, Pair객체를 반환
fun checkDefaultZipOperator() {
val colors = listOf("red", "brown", "grey")
val animals = listOf("fox", "bear", "wolf")
println(colors zip animals)
val twoAnimals = listOf("fox", "bear")
println(colors.zip(twoAnimals))
}
- collection 두개를 zip으로 생성한 결과 collection을, 변형 함수를 통해 변형하여 사용 할 수 있다.
- 이때 변형 함수의 인자는 첫번째, 두번째 collection의 item이 들어간다.
fun checkZipUsingTransformFunction() {
val colors = listOf("red", "brown", "grey")
val animals = listOf("fox", "bear", "wolf")
println(colors.zip(animals) { color, animal -> "The ${animal.capitalize()} is $color"})
}
- Pair 객체를 element의 type으로 갖는 List는, List와 List의 zip을 통해 만들어 진 것과 같다고 볼 수 있으므로
unzip() 함수를 통해 두개의 List로 분할이 가능하다
fun checkUnzipFunction() {
val numberPairs = listOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
println(numberPairs.unzip())
}
Associate
- Collection의 item으로 부터 map 객체를 생성 해 준다.
associateWith() / associateBy() 등의 함수를 사용
fun checkAssociateWithOperator() {
val numbers = listOf("one", "two", "three", "four")
println(numbers.associateWith { it.length })
}