Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

การเรียงลำดับคอลเลกชันหลายฟิลด์ใน Kotlin

ภาพรวม

ใน Kotlin สามารถเรียงลำดับคอลเลกชัน (List, Array) ตามหลายคุณสมบัติ (multiple fields) ได้อย่างง่ายดายด้วยฟังก์ชัน sortedWith() และ compareBy() จากไลบรารีมาตรฐาน

ฟังก์ชันสำคัญ

sortedWith()

คืนค่า List ที่เรียงลำดับตาม Comparator ที่ระบุ

fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): List<T>

compareBy()

สร้าง Comparator ที่เปรียบเทียบตามลำดับของ selector functions ที่ส่งเข้ามา

fun <T> compareBy(vararg selectors: (T) -> Comparable<*>?): Comparator<T>

ตัวอย่าง: เรียงนักศึกษาตามอายุ แล้วตาม GPA

data class Student(
    val name: String,
    val age: Int,
    val gpa: Double
)

fun main() {
    val students = listOf(
        Student("Student A", 18, 7.0),
        Student("Student B", 18, 6.9),
        Student("Student C", 20, 7.3),
        Student("Student D", 22, 8.3)
    )

    // เรียงตามอายุ (น้อยไปมาก) แล้วตาม GPA (น้อยไปมาก)
    val sortedStudents = students.sortedWith(
        compareBy({ it.age }, { it.gpa })
    )

    sortedStudents.forEach { student ->
        println("name: ${student.name}, age: ${student.age}, GPA: ${student.gpa}")
    }
}

ผลลัพธ์

name: Student B, age: 18, GPA: 6.9
name: Student A, age: 18, GPA: 7.0
name: Student C, age: 20, GPA: 7.3
name: Student D, age: 22, GPA: 8.3

การเรียงลำดับแบบกำหนดเอง (Descending, Null Safety)

// เรียงอายุมากไปน้อย (descending) แล้ว GPA น้อยไปมาก
val sortedDesc = students.sortedWith(
    compareBy({ it.age }, { it.gpa }).thenByDescending { it.age }
)

// จัดการค่า null (วาง null ไปท้ายสุด)
val withNulls = listOf(
    Student("A", 20, 3.5),
    Student("B", 20, 3.0),
    Student("C", 19, 3.8)
)
val nullSafe = withNulls.sortedWith(
    compareBy({ it.age }, { it.gpa }) // null จะถูกวางไว้หน้าสุด (natural order)
    // ใช้ nullsLast() เพื่อวาง null ท้ายสุด: compareBy({ it.age }, { it.gpa }).nullsLast()
)

สรุป

  • compareBy รับ selector หลายตัว และเปรียบเทียบตามลำดับที่ส่งเข้า
  • แต่ละ selector ต้องคืนค่า Comparable (Int, Double, String, Enum, etc.)
  • ใช้ thenBy, thenByDescending เพื่อต่อยอดเงื่อนไข
  • ใช้ nullsFirst(), nullsLast() ควบคุมตำแหน่งค่า null