Skip to content

Instantly share code, notes, and snippets.

@ptrdom
Created August 31, 2018 14:13
Show Gist options
  • Save ptrdom/fd4d7a4f0e8bf7c0ec8772e658a1bf66 to your computer and use it in GitHub Desktop.
Save ptrdom/fd4d7a4f0e8bf7c0ec8772e658a1bf66 to your computer and use it in GitHub Desktop.
LRUCache implementation in Scala
import scala.collection.mutable
class LRUCache(maxSize: Int) {
val map = mutable.LinkedHashMap[Int, String]()
def put(key: Int, value: String) = {
moveToBottom(key, value)
if (map.size > maxSize) {
val (firstKey, _) = map.head
map.remove(firstKey)
}
}
def get(key: Int): Option[String] = {
map.get(key).map {
value =>
moveToBottom(key, value)
value
}
}
private def moveToBottom(key: Int, value: String) = {
map.remove(key)
map.put(key, value)
}
}
val lruCache = new LRUCache(2)
lruCache.put(1, "1")
lruCache.put(2, "2")
lruCache.put(3, "3")
lruCache.get(2)
lruCache.put(4, "4")
println(lruCache.map)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment