TIL - Kotlin
[Kotlin] 유용한 List 고차함수
cocokaribou
2023. 4. 18. 16:30
컬렉션 안에 필요한 정보를 끄집어낼 때
몇 겹씩 되는 for문을 돌리는 대신 고차함수를 쓰면 편리하다.
그렇다고 소스코드에서 for문을 안 쓰는 것은 아니나
데이터의 뎁스가 깊을 때 가독성이 좋아진다는 장점이 있다.
List 를 다룰 때 유용한 고차함수들을 간략하게 정리해봤다.
예시 데이터1
data class SubCategory(
val title: String = "",
var isChecked: Boolean = false
)
all
list.all { it -> 체크하고 싶은 조건문 }
모든 요소가 조건에 해당하는지 true/ false 리턴
val isAllChecked: Boolean = subCategory.all { it -> it.isChecked } // 전부 체크됐는지 여부
count
list.count { it -> 체크하고 싶은 조건 }
조건에 해당하는 요소 개수 Int 리턴
val checkCount: Int = subCategory.count { it -> it.isChecked } // 체크된 요소 개수
filter
list.filter { it -> 필터링해서 남기고 싶은 조건 }
조건에 해당하는 요소들만 남긴 list 리턴
val filteredList = subCategory.filter { it -> it.isChecked } // 체크된 요소만 남김
find
list.find { it -> 찾고 싶은 조건 }
조건에 해당하는 요소를 nullable로 리턴
val foundElement: SubCategory? = subCategory.find { it -> it.title.contains("header") }
// title 에 "header"가 들어간 요소를 찾음
first
list.first { it -> 찾고 싶은 조건 }
조건에 해당하는 요소를 not-null 로 리턴
요소를 발견 못할 시 java.util.NoSuchElementException 예외가 나면서 터질 수도 있음
val foundElement = try {
subCategory.first { it -> it.title.contains("header") }
} catch(e: java.util.NoSuchElementException) {
null
}
map
list.map { it -> it을 수정 }
list의 요소를 수정해서 새로운 리스트를 리턴.
map 블럭의 마지막 줄에서 객체를 반드시 리턴하지 않으면 List가 아닌 Unit으로 리턴되니 유의.
subCategory.map { it.isChecked = true } // 요소를 전부 체크됨으로 수정
예시 데이터2
data class Category(
val title: String = "",
val subCategoryList: List<SubCategory>
){
data class SubCategory(
val title: String = "",
var isChecked: Boolean = false
)
}
flatMap
다차원 리스트에서 뎁스를 줄인 리스트를 얻을 수 있다.
list.flatMap { it -> it.남기고 싶은 뎁스의 리스트 }
val flattened1: List<SubCategory> = categoryList.flatMap{
it.subCategoryList
// flatMap 블럭 가장 마지막 줄에는 List<SubCategory>를 남긴다
}
val flattened2: List<String> = categoryList.flatMap{
it.subCategoryList.map { it.title }
// flatMap 블럭 가장 마지막 줄에는 List<String>을 남긴다
}
flatMap을 쓰면 원본보다 요소 개수가 줄어들 수는 있어도 늘어날 수는 없다.
728x90