안드로이드 개발 팁 #30 - Collection, MutableCollection 연산 확장 함수 filter, count, indexOfFirst, sortWith, sortedWithsteemCreated with Sketch.

시작하며...

kotlin.collections 패키지에서는 배열, 리스트 등 Collection, MutableCollection 인터페이스를 구현하는 콜렉션 클래스 관련 여러 가지 확장 함수들이 있습니다. 그 중에서 실무에 자주 사용되는 몇가지를 정리해보고자 합니다. 이들을 알아두면, 자바보다 깔끔한 코드를 만들 수 있어 좋습니다.


filter 확장 함수

이 함수는 특정 조건을 만족하는 원소들만 모아서 새로운 리스트로 리턴합니다.

val list = listOf(1, 3, 2, 5, 4)
val filteredList = list.filter { e -> (e > 3) }

count 확장 함수

이 함수는 특정 조건을 만족하는 원소들의 개수를 리턴합니다.

val list = listOf(1, 3, 2, 5, 4)
val filteredListSize = list.count { e -> (e > 3) }

indexOfFirst 확장 함수

이 함수는 특정 조건을 만족하는 최초 원소의 인덱스를 리턴합니다.

val list = listOf(1, 3, 2, 5, 4)
val indexOf3 = list.indexOfFirst { e -> (e == 3) }

sortWith 확장 함수

특정 필드 기준으로 오름차순 정렬을 실행합니다. 이 함수를 실행한 mutable list가 정렬됩니다.

val list = listOf(…)
list.sortWith(compareBy({ it.필드A }, { it.필드B }, { it.필드C }))

sortedWidth 확장 함수

특정 필드 기준으로 오름차순 정렬을 한 리스트를 리턴합니다. Immutable list만 실행 가능합니다.

val list = listOf(…)
val newList = list.sortedWith(compareBy({ it.필드A }, { it.필드B }, { it.필드C }))

예제 코드

data class Lecture(
    val lecID: String,
    val categoryID: String,
    val name: String,
    val isBookmarked: Boolean
)

var lecList = mutableListOf<Lecture>(
    Lecture("Lec00001", "Category00001", "How to Learn Java", true),
    Lecture("Lec00003", "Category00001", "How to Learn Kotlin", false),
    Lecture("Lec00002", "Category00002", "How to Learn Dart", false),
    Lecture("Lec00004", "Category00002", "How to Learn JavaScript", true)
)

fun main() {
    val category00001LecList = lecList.filter { lec -> lec.categoryID == "Category00001" }
    println("Category00001 lecture list: ")
    println(category00001LecList)
    println()

    val bookmarkedLecList = lecList.filter { lec -> lec.isBookmarked == true }
    println("\nBookmarked lecture list: ")
    println(bookmarkedLecList)
    println()

    val countOfBookmarkedLectures = lecList.count { lec -> lec.isBookmarked == true }
    println("Count of bookmarked lectures: ${countOfBookmarkedLectures}")
    println()

    val indexOfLec00002Lecture = lecList.indexOfFirst { lec -> lec.lecID == "Lec00002" }
    println("Index of Lec00002 lecture: ${indexOfLec00002Lecture}")
    println()

    lecList.sortWith(compareBy({ it.lecID }, { it.categoryID }, { it.name }, { it.isBookmarked }))
    println("Lecture list sorted with lecID, categoryID, name and isBookmarked: ")
    println(lecList)
    println()

    val newSortedLecList = lecList.sortedWith(compareBy({ it.isBookmarked }, { it.lecID }, { it.categoryID }, { it.name }))
    println("New lecture list sorted with isBookmarked, lecID, categoryID and name: ")
    println(newSortedLecList)
    println()
}

지난 안드로이드 개발 팁

Sort:  
 last year 

[광고] STEEM 개발자 커뮤니티에 참여 하시면, 다양한 혜택을 받을 수 있습니다.

Upvoted! Thank you for supporting witness @jswit.