Home > Blockchain >  how can i sort 2D mutableListof<Any> by the first element in Kotlin
how can i sort 2D mutableListof<Any> by the first element in Kotlin

Time:11-11

how can i sort 2D mutable list of array by the first element of array?

val books = mutableListOf<Any>(
  listof("abc","b",1),
  listof("abb","y",2),
  listof("abcl"."i",3)
)

i want to get sort this mutablelist by alphabetical order of the first element of each list.

output should be

[listof("abb","y",2), listof("abc","b",1), listof("abcl"."i",3) ]

CodePudding user response:

You can do

books.sortBy { (it as List<*>).first() as String }

CodePudding user response:

This is difficult, because you have very limited type information.

If you the elements of the inner lists always have three values of type String, String, Integer, you should probably use a triple:

val books = mutableListOf<Triple<String, String, Int>>(
    Triple("abc","b",1),
    Triple("abb","y",2),
        Triple("abcl","i",3)
)

books.sortBy { t -> t.first }

If the inner lists are always lists, but with different lengths and types, but it is known that the are always strings you can do something like

val books = mutableListOf<List<Any>>(
    listOf("abc","b",1),
    listOf("abb","y",2),
    listOf("abcl","i",3)
)

books.sortBy { t -> t.first() as String }

If you don't know any type information, and books is truly a MutableList<Any>, then you cannot compare: you don't what you are comparing.

  • Related