So I am getting some json data and putting it inside of a Mutable List. I have a class with id, listId, and name inside of it. Im trying to sort the output of the list by listId which are just integers and then also the name which has a format of "Item 123". Im doing the following
val sortedList = data.sortedWith(compareBy({ it.listId }, { it.name }))
This sorts the listId correctly but the names is sorted alphabetically so the numbers go 1, 13, 2, 3. How am I able to sort both the categories but make the "name" also be sorted numerically?
I think
val sortedList = data.sortedWith(compareBy(
{ it.listId },
{ it.name.substring(0, it.name.indexOf(' ')) },
{ it.name.substring(it.name.indexOf(' ') + 1).toInt() }
))
will work but it is not computationally efficient because it will call String.indexOf()
many times.
If you have a very long list, you should consider making another list whose each item has String
and Int
names.