LoginSignup
5
1

More than 3 years have passed since last update.

【Kotlin】複数の条件でオブジェクトを大小比較する

Last updated at Posted at 2020-03-22

例えば、次のようなクラスがあり、そのインスタンスを生年月日でソートしたい場合。

data class Person(
    val name: String,
    val birthYear: Int,
    val birthMonth: Int,
    val birthDayOfMonth: Int
)

次のように Comparator を生成すればよい。

val birthDateComparator: Comparator<Person> =
    compareBy<Person> { it.birthYear }
        .thenBy { it.birthMonth }
        .thenBy { it.birthDayOfMonth }

使用例:

fun main() {
    listOf(
        Person("Alice", 2000, 1, 1),
        Person("Bob", 2000, 1, 2),
        Person("Carol", 2001, 1, 1)
    )
        .shuffled()
        .sortedWith(birthDateComparator)
        .map { it.name }
        .also {
            println(it) // > [Alice, Bob, Carol]
        }
}

別の書き方:

val birthDateComparator: Comparator<Person> =
    Comparator<Person> { a, b -> a.birthYear.compareTo(b.birthYear) }
        .thenComparator { a, b -> a.birthMonth.compareTo(b.birthMonth) }
        .thenComparator { a, b -> a.birthDayOfMonth.compareTo(b.birthDayOfMonth) }
5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1