본문 바로가기
Android

[Kotlin] 코틀린 기본 문법 5 (배열 응용)

by bryan.oh 2023. 7. 20.
반응형

 

배열 정렬

listOf() / mutableListOf()

    val list = listOf(1, 5, 4, 6, 3, 2)
    val sorted = list.sorted().reversed()
    println("sorted : $sorted")
    // sorted : [6, 5, 4, 3, 2, 1]
    
    val list2 = mutableListOf(1, 5, 4, 6, 3, 2)
    list2.sort()
    list2.reverse()
    println("sorted : $list2")
    // sorted : [6, 5, 4, 3, 2, 1]

 

sortedWith

    val list = listOf("kevin", "steve", "john", "mark", "jadon")

    val alphabetOrder = list.sorted()
    println("Alphabet order: $alphabetOrder")
    // Alphabet order: [jadon, john, kevin, mark, steve]

    val comparator : Comparator<String> = compareBy { it.length }
    val lengthOrder = list.sortedWith(comparator)
    println("Length order: $lengthOrder")
    // Length order: [john, mark, kevin, steve, jadon]

 

Data Class List 정렬하기

data class Person(val name: String, val age: Int, val power: Int)

fun main() {
	val people = mutableListOf(
        Person("kevin", 9, 100), 
        Person("John", 40, 96),
        Person("Jacob", 9, 90), 
        Person("Teddy", 30, 98),
        Person("Bryan", 40, 120),
        Person("Dyson", 20, 98)
    )
    people.sortWith(compareBy<Person> { it.age }.thenBy { it.power }.thenBy { it.name })

    people.forEach { println(it) }
}
/*
Person(name=Jacob, age=9, power=90)
Person(name=kevin, age=9, power=100)
Person(name=Dyson, age=20, power=98)
Person(name=Teddy, age=30, power=98)
Person(name=John, age=40, power=96)
Person(name=Bryan, age=40, power=120)
*/

 

find

val ml = mutableListOf("top", "left", "right", "bottom", "upper", "hellow")
val res = ml.find{it.length == 5}
println(res)
// right

val res2 = ml.findLast{it.length == 5}
println(res2)
// upper

val res3 = ml.findLast{it.startsWith("bot")}
println(res3)
// bottom

val res4 = ml.findLast{it.contains("pp")}
println(res4)
// upper

val res5 = ml.findLast{it.endsWith("ow")}
println(res5)
// hellow
mutableListOf, listOf, arrayListOf, arrayOf 결과는 모두 같음

 

[Android] - [Kotlin] 코틀린 기본 문법 1 (변수, 자료형)

[Android] - [Kotlin] 코틀린 기본 문법 2 (배열의 모든 것)

[Android] - [Kotlin] 코틀린 기본 문법 3 (함수)

[Android] - [Kotlin] 코틀린 기본 문법 4 (조건문, 반복문)

[Android] - [Kotlin] 코틀린 기본 문법 5 (배열 응용)

[Android] - [Kotlin] findViewById 대신에 View binding

728x90
반응형

댓글