Home > Software design >  How to sort list of objects by various object variables in kotlin?
How to sort list of objects by various object variables in kotlin?

Time:12-12

Having this object:

class Data (region: String, language: String, version: String)

with these instances:

var data1 = Data("Spain", "En, Pl", "")
var data2 = Data("Spain", "Ru, Es", "")
var data2 = Data("France", "Fr, En", "v1.0")
var data3 = Data("Germany", "", "v1.1")

and having an array of that object: var list = mutableListOf(data1, data2, data3, data3)

my idea is to order the list by these factors, ordered by importance, first factor is the most important, then, the others:

order factor 1: if (region == "Spain") is the most important factor, anything with that condition must be before other regions. And if is not, then it should compare if (region == "Europe"). And if not, then should it compare if (region == "World")

order factor 2: if (language.contains("Es")) is the second most important factor

order factor 3: version. v1.1 is higher so must be in a more important possition that v1.0. Numbers can be infinite, 1.1 and 1.0 are just samples. It must put higher versions before lower versions

How can this be implemented?

I tryed this, with totally wrong results:

list.sortedWith(compareBy({ it.region == "Spain"}, { it.language?.contains("Es") }, { it.version }))

CodePudding user response:

You can just provide 'numeric scores' for region/language/version -- exactly as you've described in your question. And because compareBy sorts elements in ascending order, lower numbers will be first.

val sorted = list.sortedWith(
    compareBy<Data>(
        {
            when (it.region.lowercase()) {
                "spain" -> 0
                "europe" -> 1
                "world" -> 2
                else -> 3
            }
        },
        {
            when {
                it.language.lowercase().contains("es") -> 0
                else -> 1
            }
        }
    ).thenByDescending {
        it.version
    }
)
  • Related