Created
August 31, 2018 14:13
-
-
Save ptrdom/fd4d7a4f0e8bf7c0ec8772e658a1bf66 to your computer and use it in GitHub Desktop.
LRUCache implementation in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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