Skip to content

Instantly share code, notes, and snippets.

@gpeal
Created July 24, 2018 06:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpeal/3cf0907fc80094a833f9baa309a1f627 to your computer and use it in GitHub Desktop.
Save gpeal/3cf0907fc80094a833f9baa309a1f627 to your computer and use it in GitHub Desktop.
/**
* Returns a new immutable map with the provided keys set/updated.
*/
fun <K, V> Map<K, V>.copy(vararg pairs: Pair<K, V>) = HashMap<K, V>(size + pairs.size).apply {
putAll(this@copy)
pairs.forEach { put(it.first, it.second) }
}
/**
* Returns a new map with the provided keys removed.
*/
fun <K, V> Map<K, V>.delete(vararg keys: K): Map<K, V> {
// This should be slightly more efficient than Map.filterKeys because we start with a map of the
// correct size rather than a growing LinkedHashMap.
return HashMap<K, V>(size - keys.size).apply {
this@delete.entries.asSequence()
.filter { it.key !in keys }
.forEach { put(it.key, it.value) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment