Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- android exoplayer
- ktor api call
- Python
- video caching
- AWS EC2
- kotlin list
- ktor client
- ListAdapter DiffUtil
- build with ai
- doc2vec
- list map
- getChangePayload
- llm
- 유튜브
- android
- ChatGPT
- ExoPlayer
- map
- ListAdapter
- 안드로이드
- 유튜브 요약
- exoplayer cache
- DiffUtil.ItemCallback
- android custom view
- FastAPI
- 스피너
- kotlin collection
- 시행착오
- Zsh
- android ktor
Archives
- Today
- Total
버튼 수집상
[Kotlin] 유용한 List 고차함수 본문
컬렉션 안에 필요한 정보를 끄집어낼 때
몇 겹씩 되는 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
'TIL - Kotlin' 카테고리의 다른 글
[Kotlin] RxJava의 mergeDelayError를 Coroutine Flow로 만들기 Coroutine Flow merge (0) | 2024.01.09 |
---|---|
[Kotlin] List.map 파헤치기 (0) | 2023.07.20 |
[Kotlin] 유용한 Collection 함수 (0) | 2023.07.04 |
[Kotlin] 코틀린 코드 스니펫 돌려보기 (0) | 2023.06.26 |
[Kotlin] List.flatMap 리스트 고차함수 (0) | 2023.01.30 |