Search code examples
sortingkotlinarraylistcomparison

How to create a sorted merged list from two diffrent ArrayList of Objects based on a common value field in Kotlin?


I have two ArrayLists of different Data classes as given below:

class Record{
    var id: Long = 0
    var RecordId: Int = 0
    var Record: String? = null
    var title: String? = null
    var description: String? = null
    var longDate: Long = 0
}

class Type{
    var id: Long = 0
    var typeId: Int = 0
    var subTypeId: Int = 0
    var typeString: String? = null
    var longDate: Long = 0
}

var recordsList: ArrayList<Record>
var typesList: ArrayList<Type>

Now, I want a merged list of these two which will be sorted based on a common field in both the Objects i.e. longDate. I have tried .associate , sortedBy, sortedWith(compareBy<>) etc. but could not achieve the desired result.

Here, also there is one point to note is that while comparing the two lists it is possible that one on them may be empty.


Solution

  • This will produce a List<Any> with all items sorted by longDate:

    (recordsList + typesList)
        .sortedBy { 
            when (it) {
                is Record -> it.longDate
                is Type -> it.longDate
                else -> error("")
            }
        }
    

    Or you might consider creating an interface that has val longDate: Long that both of these classes implement. Then you wouldn't need the when expression, and your List would be of the type of the interface.