I want to sort a list by the elements of another list. So the second list should explicitly define the order of the resulting (ordered) list.
The best I came up with is this:
fun main() {
val things = setOf(Thing(2, "x"), Thing(1, "y"), Thing(3, "z"), Thing(4, "a"))
val desiredOrder = listOf(3, 4, 1, 2)
val sortedThings = things.sortedWith { a, b ->
desiredOrder.indexOf(a.id).compareTo(desiredOrder.indexOf(b.id))
}
println(sortedThings)
// prints: [Thing(id=3, name=z), Thing(id=4, name=a), Thing(id=1, name=y), Thing(id=2, name=x)]
}
data class Thing(val id: Int, val name: String)
However, compared to Guava’s Ordering.explicit
it is quite verbose:
List<User> users = userDao.loadUsersWithIds(userIds);
Ordering<User> orderById = Ordering.explicit(userIds).onResultOf(UserFunctions.getId());
return orderById.immutableSortedCopy(users);
Is there a better way in Kotlin?