copy
Returns an immutable copy of this map entry with the same key and value.
The returned entry is not connected to the map this entry was obtained from. The key and value of the returned entry remain the same even after the map the original entry was obtained from was modified.
Since Kotlin
2.3Return
An immutable entry that is equal to this entry but not connected to any map. The function may return the same entry if this entry was obtained from the call to copy. The returned entry, while still implementing Map.Entry interface, may not be an instance of the same class as the original entry.
Samples
import kotlin.test.*
import java.util.*
fun main() {
//sampleStart
val map = mutableMapOf(1 to "a", 2 to "b", 3 to "c", 4 to "d")
val selectedEntries = map.entries.filter { it.key % 2 == 0 }
println(selectedEntries) // [2=b, 4=d]
// This may throw: "The backing map has been modified after this entry was obtained."
// because the map is structurally modified as soon as the first one entry is removed
// map.entries.removeAll(selectedEntries)
val selectedEntriesCopy = selectedEntries.map { it.copy() }
map.entries.removeAll(selectedEntriesCopy)
println(map) // {1=a, 3=c}
// Copied entries continue to be valid even after the original map is cleared
map.clear()
println(selectedEntriesCopy) // [2=b, 4=d]
//sampleEnd
}