Search code examples
androidsortingkotlinpojo

sortwith one of the POJO values?


I have random pojo values, and I want to sort by one of the POJO values, the structure of the values ​​I want to sort is as follows: A-1, A-2, A-3, A-4, A-5, .. .

I've tried to sort it but the value is really in order only between A-1 to A-9, while the value for A-10 is always under A-1.

here's the code I use:

temp.sortWith { lhs, rhs ->
  rhs?.blok_kamar?.let {
  lhs?.blok_kamar?.compareTo(
    it, false
  )}!!
}

Please help.


Solution

  • This is how lexicographical ordering works. "1000" is less than "2", despite 1000 being greater than 2. Look at the quotes. It seems like your A-1, A-2, ..., A-10 are Strings. You need to extract the numbers from those identifiers and compare them as Ints:

    data class Data(val id: String)
    
    fun main() {
        val list = mutableListOf(
            Data("A-1"),
            Data("A-10"),
            Data("A-2"),
            Data("A-30"),
            Data("A-3")
        )
    
        list.sortBy { it.id.substring(it.id.indexOf("-") + 1).toInt() }
        println(list)
    }
    

    This prints:

    [Data(id=A-1), Data(id=A-2), Data(id=A-3), Data(id=A-10), Data(id=A-30)]