Kotlin simple and complex sorting

We can use Iterable<T>.sortedBy(…) for simple sorting in Kotlin. But, Actually, there is no only case that can be sorted simply in real life. We need various ways of sorting items. Even if sorting case is too complex, we can use SortedWith to sort it.


Simple sorting

We want to sort people by their ages. Then, we can sort them by using SortedBy . Below is the code about this case.

Complex sorting

In Upper case, they are sorted by their ages. but that would be sorted only by their ages even if new property is added to Person class. What should we do if we want to filter them by new condition? In this case, we can use Iterable<T>.sortedWith(…): List<T>.

Let’s suppose that we have to pick 2 people from the list. We would check two property to compare each other: Age, Score. They would be sorted in order of highest score and age. In this case, there are two conditions: [Descending by age], [Descending by score].And, we can deal with this case with below code.