Scala bounded LRU cache with mutable map
Scala
import scala.collection.mutable
final class LruCache[K, V](maxSize: Int):
require(maxSize > 0, "maxSize must be positive")
private val store = mutable.LinkedHashMap.empty[K, V]
def get(key: K): Option[V] =
store.remove(key).map { value =>
store.put(key, value)
value
}
def put(key: K, value: V): Unit =
store.remove(key)
store.put(key, value)
if store.size > maxSize then store.remove(store.head._1)