반응형

코틀린 콜렉션 타입 변환 예제

 

코틀린은 다양한 콜렉션 타입 변환 함수들을 제공하여, 필요에 따라 콜렉션의 타입을 변경하거나 데이터를 가공할 수 있도록 지원합니다.

 

다음은 자주 사용되는 콜렉션 타입 변환 예제와 함께 각 함수에 대한 설명입니다.

 

1. toList(), toSet(), toMap()

  • toList() : 컬렉션을 List로 변환합니다.
  • toSet() : 컬렉션을 Set으로 변환하여 중복 요소를 제거합니다.
  • toMap() : 컬렉션을 Map으로 변환합니다. 이때, 컬렉션의 요소는 키-값 쌍을 가지는 Pair 타입이어야 합니다.
val numbers = listOf(1, 2, 3, 4, 5, 1)

val numberList = numbers.toList() // List로 변환
println(numberList) // 출력: [1, 2, 3, 4, 5, 1]

val numberSet = numbers.toSet() // Set으로 변환 (중복 제거)
println(numberSet) // 출력: [1, 2, 3, 4, 5]

val numberMap = numbers.mapIndexed { index, value -> index to value }.toMap() // Map으로 변환
println(numberMap) // 출력: {0=1, 1=2, 2=3, 3=4, 4=5, 5=1} 

 

2. map()

  • map() : 컬렉션의 각 요소에 주어진 함수를 적용하여 새로운 컬렉션을 생성합니다.
val numbers = listOf(1, 2, 3, 4, 5)

val squaredNumbers = numbers.map { it * it } // 각 요소를 제곱하여 새 리스트 생성
println(squaredNumbers) // 출력: [1, 4, 9, 16, 25]

 

3. flatMap()

  • flatMap() : 컬렉션의 각 요소에 주어진 함수를 적용하고, 그 결과를 하나의 컬렉션으로 병합합니다.
val nestedList = listOf(listOf(1, 2), listOf(3, 4, 5))

val flattenedList = nestedList.flatMap { it } // 중첩된 리스트를 하나로 병합
println(flattenedList) // 출력: [1, 2, 3, 4, 5]

 

4. filter()

  • filter() : 컬렉션에서 주어진 조건을 만족하는 요소만 추출하여 새로운 컬렉션을 생성합니다.
val numbers = listOf(1, 2, 3, 4, 5)

val evenNumbers = numbers.filter { it % 2 == 0 } // 짝수만 추출
println(evenNumbers) // 출력: [2, 4]

 

5. associate() / associateBy() / associateWith()

  • associate() : 컬렉션의 각 요소를 키-값 쌍으로 변환하여 Map을 생성합니다.
  • associateBy() : 컬렉션의 각 요소에서 키를 추출하여 Map을 생성합니다. 값은 요소 그대로 사용됩니다.
  • associateWith() : 컬렉션의 각 요소에서 값을 추출하여 Map을 생성합니다. 키는 요소 그대로 사용됩니다.
val names = listOf("John", "Jane", "Mike")

val nameMap = names.associate { it to it.length } // 이름을 키로, 길이를 값으로 하는 Map 생성
println(nameMap) // 출력: {John=4, Jane=4, Mike=4}

val nameMapBy = names.associateBy { it.first() } // 이름의 첫 글자를 키로, 이름을 값으로 하는 Map 생성
println(nameMapBy) // 출력: {J=John, M=Mike}

val nameMapWith = names.associateWith { it.length } // 이름을 키로, 길이를 값으로 하는 Map 생성
println(nameMapWith) // 출력: {John=4, Jane=4, Mike=4}

 

6. partition()

  • partition() : 컬렉션을 주어진 조건을 만족하는 요소와 만족하지 않는 요소의 두 리스트로 분할합니다.
val numbers = listOf(1, 2, 3, 4, 5)

val (even, odd) = numbers.partition { it % 2 == 0 } // 짝수와 홀수로 분할
println(even) // 출력: [2, 4]
println(odd) // 출력: [1, 3, 5]

 

7. zip()

  • zip() : 두 컬렉션의 요소를 쌍으로 묶어 새로운 컬렉션을 생성합니다.
val names = listOf("John", "Jane", "Mike")
val ages = listOf(30, 25, 40)

val nameAgePairs = names.zip(ages) // 이름과 나이를 쌍으로 묶음
println(nameAgePairs) // 출력: [(John, 30), (Jane, 25), (Mike, 40)]

 

8. flatten()

  • flatten() : 중첩된 컬렉션을 하나의 컬렉션으로 병합합니다.
val nestedList = listOf(listOf(1, 2), listOf(3, 4, 5))

val flattenedList = nestedList.flatten() // 중첩된 리스트를 하나로 병합
println(flattenedList) // 출력: [1, 2, 3, 4, 5]

 

 

더 자세한 내용은 다음 링크를 참조하세요.

 

🔎 https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/map.html: Google 검색

 

www.google.com

 

 

반응형

+ Recent posts