如何对其中包含数字的字符串进行数字排序?

How to sort string with numbers in it numerically?

所以我正在获取一些 json 数据并将其放入可变列表中。我有一个 class,其中包含 id、listId 和名称。我试图按 listId 对列表的输出进行排序,listId 只是整数,然后还有格式为“Item 123”的名称。我在做以下事情

val sortedList = data.sortedWith(compareBy({ it.listId }, { it.name }))

这对 listId 进行了正确排序,但名称是按字母顺序排序的,因此数字为 1、13、2、3。我如何才能对两个类别进行排序,同时使“名称”也按数字排序?

我觉得

val sortedList = data.sortedWith(compareBy(
    { it.listId },
    { it.name.substring(0, it.name.indexOf(' ')) },
    { it.name.substring(it.name.indexOf(' ') + 1).toInt() }
))

可以,但计算效率不高,因为它会多次调用 String.indexOf()

如果您的列表很长,您应该考虑制作另一个列表,其中每个项目都有 StringInt 个名称。