HelloCW
HelloCW

Reputation: 2255

How can I sort a table based two fields using Anko in Kotlin?

I use Anko to operate SQLite table, I hope to sort a list based the field isFavorite first, then based the createdDate

For example, input Source Data, and I get the Sort Result Data

But the code return myList.sortedBy{it.isFavorite}.sortedBy{ it.createdDate} can't get the correct result, how can I fix it?

Source Data

enter image description here

Sort Result Data (I hope to get )

enter image description here

Structure

data class MRecord (
    var _id: Long,     
    var isFavorite: Bool,   
    var createdDate: Long
)

Code

var myList=select(tableName).parseList { MDBRecord(HashMap(it)) }        
return myList.sortedBy{it.isFavorite}.sortedBy{ it.createdDate}

Added Content

To madhead: Thanks!

data class MRecord(
    var id: Long,
    var isFavorite: Long,
    var createdDate: Long
)


val list = listOf(
        MRecord(1, 1, 100),
        MRecord(2, 0, 200),
        MRecord(3, 1, 300)
)

I hope to get the result

1, 1, 100
3, 1, 300
2, 0, 200

but the code println(list.sortedWith(compareBy({ !it.isFavorite }, MRecord::createdDate))) will not work because isFavorite is Long, how can I fix it?

Upvotes: 3

Views: 217

Answers (1)

madhead
madhead

Reputation: 33422

You're right, myList.sortedBy{it.isFavorite}.sortedBy{ it.createdDate} will not give you correct results, because it is basically equal to myList.sortedBy{ it.createdDate} (only the last sorting applies). What you need is a comparator that takes multiple fields into account and looks like compareBy is what you need:

Creates a comparator using the sequence of functions to calculate a result of comparison. The functions are called sequentially, receive the given values a and b and return Comparable objects. As soon as the Comparable instances returned by a function for a and b values do not compare as equal, the result of that comparison is returned from the Comparator.

So, check this out:

data class MRecord(
    var id: Long,
    var isFavorite: Boolean,
    var createdDate: Long
)

fun main(args: Array<String>) {
    val list = listOf(
        MRecord(1, true, 10),
        MRecord(2, false, 20),
        MRecord(3, true, 30)
    )

    println(list)

    println(list.sortedWith(compareBy({ !it.isFavorite }, MRecord::createdDate)))
}

Note how you can mix lambdas and function references.

Edit for Long isFavorite:

data class MRecord(
    var id: Long,
    var isFavorite: Long,
    var createdDate: Long
)

fun main(args: Array<String>) {
    val list = listOf(
        MRecord(1, 1, 100),
        MRecord(2, 0, 200),
        MRecord(3, 1, 300)
    )

    println(list.sortedWith(compareByDescending<MRecord> { it.isFavorite }.then(compareBy(MRecord::createdDate))))
}

Upvotes: 1

Related Questions