Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of object in kotlin with custom order?

I have an array of object User(val name: String, val role: String). Role can be: leader, student, teacher, parent. And should be sorted in that order. I've read some article about Comparator but haven't figure out how they work. Can you please add some explanation too?

like image 861
Dr4ke the b4dass Avatar asked Dec 19 '19 01:12

Dr4ke the b4dass


People also ask

How do you sort an arrayList of objects in descending order in Kotlin?

Using sort() function The sort() function is the recommended way to in-place sort elements of the specified list. The sorting is done according to the natural ordering of its elements. To sort the list in reverse order, switch to the sortDescending() function.


1 Answers

You can instantiate a HashMap for indicating roles priority:

private val roles: HashMap<String, Int> = hashMapOf(
    "Leader" to 0,
    "Student" to 1,
    "Teacher" to 2,
    "Parent" to 3
)

fun sortUsers(users: ArrayList<User>): ArrayList<User> {
    val comparator = Comparator { o1: User, o2: User ->
        return@Comparator roles[o1.role]!! - roles[o2.role]!!
    }
    val copy = arrayListOf<User>().apply { addAll(users) }
    copy.sortWith(comparator)
    return copy
}

In the comparator, if the result of the subtraction is negative, it will sort it in the order [o1, o2]. Otherwise, [o2, o1]. So in this case, it will sort your list in an ascending manner (since we have the highest priority as 0 - Leader as indicated in the HashMap).

For example, if we have o1 as Teacher and o2 as Leader, the result of the comparator will be: 2 - 0 = 2 which is a positive integer. Hence, it is sorted as [o2 (Leader), o1 (Teacher)]. Reversing the roles however yields the opposite result: 0 - 2 = -2 and hence it will be ordered [o1 (Teacher), o2 (Leader)].

You can verify this result with:

fun main(args: Array<String>) {
    val users = arrayListOf(
        User("john", "Student"),
        User("tim", "Teacher"),
        User("nice", "Student"),
        User("hey", "Leader"),
        User("you", "Parent")
    )
    println(sortUsers(users))
}

Which prints out: [User(name=hey, role=Leader), User(name=john, role=Student), User(name=nice, role=Student), User(name=tim, role=Teacher), User(name=you, role=Parent)]

like image 195
Christilyn Arjona Avatar answered Nov 02 '22 23:11

Christilyn Arjona