Home > database >  Sorting arraylist and returning an arraylist (not a list) - Kotlin
Sorting arraylist and returning an arraylist (not a list) - Kotlin

Time:12-03

I'm trying to display sorted information using a RecyclerView. To do so, I've got an ArrayList of custom datatype. I want to sort the data in the ArrayList by descending order, using one of the fields in the ArrayList. I'm familiar with the methods that are already available (sortWith, sortBy, sortByDescending, etc) but unfortunately, they all change from ArrayList to List and this stops the recycler view from working. Ideally, I'd like to preserve the ArrayList because I need it for other processes that I carry out later in the project.

WHAT I'M TRYING TO ACHIEVE:

INPUT: arrayListName = ArrayList<CustomType>

PROCESS: [sort by decending order of arrayListName.firstName]

OUTPUT: return ArrayList<CustomType>

I've tried casting the List (shown below) to ArrayList, but that throws the below error:

java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList 

Line of code that throws the error (I've tried various methods, but they all throw an exception on that line):

val sortedModel = model.sortedWith(compareBy { it.name}) as ArrayList<Model>

Any help is appreciated(:

I'm happy with a java solution too because I understand it and can easily implement from java to kotlin.

CodePudding user response:

You can not cast a List to an ArrayList directly. If you want to convert a List to ArrayList, you can do it this way:

val sortedModel = model.sortedByDescending { it.name }.toCollection(ArrayList())

CodePudding user response:

This will help you

val list = arrayList.sortedByDescending { it.firstName.length }
        result.addAll(list)

Full code:

val arrayList: ArrayList<CustomType> = arrayListOf()
val result: ArrayList<CustomType> = arrayListOf()
arrayList.add(CustomType("Aadddd"))
arrayList.add(CustomType("Ccd"))
arrayList.add(CustomType("Bbdd"))
arrayList.add(CustomType("Ffddd"))
arrayList.add(CustomType("Dd"))

val list = arrayList.sortedByDescending { it.firstName.length }
result.addAll(list)

Output:

SORT [{"firstName":"Aadddd"},{"firstName":"Ffddd"},{"firstName":"Bbdd"},{"firstName":"Ccd"},{"firstName":"Dd"}]

CodePudding user response:

Use sortWith instead it does inplace , try this

data class A(
    val x : Int
)

fun main(args: Array<String>) {
    var a = arrayListOf( A(1) ,A(2) ,A(3) ,A(4) )
    a.sortWith(compareByDescending { it.x })
    assert( a is ArrayList )
    println(a)
}

try yourself

  • Related