Skip to content

Instantly share code, notes, and snippets.

@vovahost
Created November 11, 2020 00:01
Show Gist options
  • Save vovahost/75567435c7571328dda8727698071cb5 to your computer and use it in GitHub Desktop.
Save vovahost/75567435c7571328dda8727698071cb5 to your computer and use it in GitHub Desktop.
import java.util.*
class LRUCache<K, T>(private val capacity: Int) {
private val map: LinkedHashMap<K, T> = LinkedHashMap()
operator fun get(key: K): T? {
val value = map[key]
if (value != null) {
this[key] = value
}
return value
}
operator fun set(key: K, value: T?) {
when {
// Null value provided, remove the key-value from the cache.
value == null -> {
map.remove(key)
}
// The cache already contains the key, remove it before inserting, to rearrange to the top.
map.containsKey(key) -> {
map.remove(key)
map[key] = value
}
// Max capacity reached, remove the oldest item before inserting the value.
map.size == capacity -> {
val it = map.keys.iterator()
it.next()
it.remove()
map[key] = value
}
else -> {
map[key] = value
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment