Home > Back-end >  Prevent mutableSet order change in Kotlin
Prevent mutableSet order change in Kotlin

Time:11-26

I am using a Mutable set of Strings to store some data whose order I dont want to change, by using preferenceEditObject.putStringSet() method. Although I add and remove data from the set, but the order should remain the same.

private fun getStrings(): MutableSet<String>? {
        return preferenceObject.getStringSet("initList", mutableSetOf())
    }
    private fun setStrings(list: MutableSet<String>?) {
        preferenceEditObject.putStringSet("initList",list).apply()
    }

But when I use the getStrings() method, the order of elements gets changed. What should I do?

CodePudding user response:

When writing, store the index together with the value, and when reading, sort by this index

private fun getStrings(): Set<String> {
    return preferenceObject.getStringSet("initList", setOf())!!
        .map { it.split(":", limit = 2).let { (index, value) -> index.toInt() to value } }
        .sortedBy { it.first }
        .mapTo(mutableSetOf()) { it.second }
}

private fun setStrings(list: Set<String>) {
    preferenceEditObject.putStringSet("initList", list.mapIndexedTo(mutableSetOf()) { index, s -> "$index:$s" }).apply()
}
  • Related