LoginSignup
2

More than 3 years have passed since last update.

Kotlinの関数型言語を利用したモデルソート

Last updated at Posted at 2019-12-17

関数型言語を利用して、モデルのソートを行いたい時に、意外と探しても見つからない。単体でのソートは?複数ソートは?モデルをソートしてみる。

準備

アカウントのデータモデルを用意する

data class Account (
    val id: Int,
    val name: String,
    val age: Int
)

上記のデータモデルをリストに追加する。

import java.util.*

fun main() {
    // 初期化
    var list = ArrayList<Account>()
    list.add(Account(1,"一郎", 35))
    list.add(Account(4,"四郎", 41))
    list.add(Account(3,"三郎", 23))
    list.add(Account(5,"五郎", 41))
    list.add(Account(2,"二郎", 19))

    // ※1 ここにソートのコードを書く

    // 結果表示
    list.forEach{println(it)}
}

実行結果は、ソートを実行してないため、リストに追加した順番で表示される。

Account(id=1, name=一郎, age=35)
Account(id=5, name=五郎, age=41)
Account(id=3, name=三郎, age=23)
Account(id=4, name=四郎, age=41)
Account(id=2, name=二郎, age=19)

単体ソート(昇順)

ageの情報で、単体ソートの昇順を行う。下記のコードを準備の※1に追加する。

list.sortBy { it.age }

実行結果
ソートの値が同等の場合は、リストの追加した順番になる

Account(id=2, name=二郎, age=19)
Account(id=3, name=三郎, age=23)
Account(id=1, name=一郎, age=35)
Account(id=5, name=五郎, age=41)
Account(id=4, name=四郎, age=41)

単体ソート(降順)

ageの情報で、単体ソートの降順を行う。

list.sortByDescending { it.age }

実行結果
ソートの値が同等の場合は、リストの追加した順番になる

Account(id=5, name=五郎, age=41)
Account(id=4, name=四郎, age=41)
Account(id=1, name=一郎, age=35)
Account(id=3, name=三郎, age=23)
Account(id=2, name=二郎, age=19)

複数ソート(全て昇順)

第一ソートをageの昇順にして、第二ソートにはidの昇順を設定する。

list.sortWith(compareBy({ it.age }, { it.id }))

実行結果

Account(id=2, name=二郎, age=19)
Account(id=3, name=三郎, age=23)
Account(id=1, name=一郎, age=35)
Account(id=4, name=四郎, age=41)
Account(id=5, name=五郎, age=41)

複数ソート(昇順と降順の混在)

第二を降順にしてみよう。

list.sortWith(compareBy<Account>{ it.age }.thenByDescending{ it.id })

実行結果

Account(id=2, name=二郎, age=19)
Account(id=3, name=三郎, age=23)
Account(id=1, name=一郎, age=35)
Account(id=4, name=四郎, age=41)
Account(id=5, name=五郎, age=41)

最後に

ソートも色々なパターンが可能になっている。また、直感的に何をしたいのか理解ができるので、ソースをみて判断することが容易になる。ソート条件が第二までのみですが、第三以降作る時も指定キーを追加すれば問題ない。

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
2