Jaakko
Jaakko

Reputation: 21

How to sort string with numbers in it numerically?

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?

Upvotes: 1

Views: 826

Answers (2)

Amit Desale
Amit Desale

Reputation: 1291

stringtoSort = "you5", "how3", "hello1", "are4", "world2"//

class Test(val title:String) {   override fun toString(): String {
    return "$title"   } }



fun extractInt(s: Test): Int {
    val num = s.title.replace("\\D".toRegex(), "")
    // return 0 if no digits found
    return if (num.isEmpty()) 0 else Integer.parseInt(num) }fun main() {    // var sortData = null   val list= listOf<Test>(Test("you5"), Test("how3"), Test("hello1"), Test("are4"), Test("world2")) var sortData = list.sortedWith( object : Comparator<Test> { override fun compare(o1: Test, o2: Test): Int {
    return extractInt(o1) - extractInt(o2) } }

)

    println(sortData ) }

Upvotes: 0

Naetmul
Naetmul

Reputation: 15552

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.

Upvotes: 2

Related Questions