Skip to content
Advertisement

Sorting arraylist and returning an arraylist (not a list) – Kotlin

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.

Advertisement

Answer

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())
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement