Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save happy-bracket/f4777738dcef24dae4e46fab1b25a1af to your computer and use it in GitHub Desktop.
Save happy-bracket/f4777738dcef24dae4e46fab1b25a1af to your computer and use it in GitHub Desktop.
SetBackedMap
class SetBackedMap<K, V>(private val set: Set<Map.Entry<K, V>>) : Map<K, V> {
override val entries: Set<Map.Entry<K, V>> = set
override val keys: Set<K> = set.map { (key, _) -> key }.toSet()
override val size: Int = set.size
override val values: Collection<V> = set.map { (_, value) -> value }
override fun containsKey(key: K): Boolean {
return set.any { (possibleKey, _) -> possibleKey == key }
}
override fun containsValue(value: V): Boolean {
return set.any { (_, possibleValue) -> possibleValue == value }
}
override fun get(key: K): V? {
return set.find { (possibleKey, _) -> possibleKey == key }?.value
}
override fun isEmpty(): Boolean {
return set.isEmpty()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment