Home > Software design >  How to get the current and next item at the same time from MutableMap using Kotlin?
How to get the current and next item at the same time from MutableMap using Kotlin?

Time:10-26

I would like to store information such as rowid (key) and orderId (value) in MutableMap. Then iterate through the MutableMap and get the current item key and value and the next item key and value. The reason for that is that while I am iterating through the Map I am changing the value of the first item using the second item value or I am changing the value of the second item value using the first item value.

Example:

    val mutableMap: MutableMap<Int, Int> = mutableMapOf<Int, Int>()
    mutableMap[350] = 0
    mutableMap[351] = 1
    mutableMap[352] = 2
    mutableMap[353] = 3
    mutableMap.put(354, 4)
    mutableMap.put(355, 5)
    mutableMap.put(356, 6)

    for (key in mutableMap.keys) {
        Log.d("print data", "print data, Key = ${key}, Value = ${mutableMap[key]}")
    }

How to get this item: myLinkedHashMap[450] = 0 and this item myLinkedHashMap[453] = 3 information at the same time so I can swap the value between them ?

CodePudding user response:

Although the Map and MutableMap interfaces do not claim to be ordered, the specific implementation used by mutableMapOf is ordered anyway. This is guaranteed because it is declared in the documentation of the function. So if you are working with a MutableMap that you declared locally with mutableMapOf, then you know it is ordered. If you are working with a MutableMap that was passed to you from some other class, then you cannot be sure it is ordered. But that should be a pretty rare occurrence since it is poor encapsulation to pass mutable collections between classes.

To iterate a map that is ordered in pairs, you can use zipWithNext on the keys. This call creates a copy of the list of keys, so you can safely mutate the map inside the loop. This is like a moving window of pairs--each element besides the first and last will appear in two different pairs, once as the second element and then once as the first element.

for ((keyA, keyB) in mutableMap.keys.zipWithNext()) {
    
}

If you want to iterate exclusive pairs, you can use chunked(2) instead of zipWithNext(), but you would need to be sure you only chunk an even number of elements:

for ((keyA, keyB) in mutableMap.keys.take(mutableMap.size - mutableMap.size % 2).chunked(2)) {

}

// or

for (keys in mutableMap.keys.chunked(2)) {
    if (keys.size == 1) continue
    val (keyA, keyB) = keys
    
}
  • Related