Search code examples
kotlincollections

Prevent mutableSet order change in Kotlin


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?


Solution

  • 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()
    }