Remove older entry from scala LinkedHashMap

I am trying to use scala LinkedHashMapas an LRU cache, but I am not sure how to delete the oldest record of such a card. I know java LinkedHashMaphas a method removeEldestEntry, but it doesn't seem like a similar method exists for scala's implementation. I would prefer not to convert to a Java implementation to access removeEldestEntry. How can I achieve this?

+4
source share
2 answers

This will do what you want:

def removeOldestEntry[K](m: scala.collection.mutable.LinkedHashMap[K, _]): m.type =
  m -= m.head._1

(Kudos to Jasper-M to indicate what headwill give the oldest record)

+2
source

You can do it as follows:

    object myApp {
      def main(args: Array[String]) {
        val myMap = new MyLinkedHashMap[Int,String]() 
        myMap.add(1, "a")   // Map(1 -> a)
        myMap.add(2, "b")   // Map(1 -> a, 2 -> b)
        myMap.add(3, "c")   // Map(1 -> a, 2 -> b, 3 -> c)
        myMap.add(4, "d")   // Map(1 -> a, 2 -> b, 3 -> c, 4 -> d)
        myMap.removeEldest  // Map(2 -> b, 3 -> c, 4 -> d)
        myMap.get(2)        // Map(3 -> c, 4 -> d, 2 -> b)
        myMap.removeEldest  // Map(4 -> d, 2 -> b)
  }
}

    class MyLinkedHashMap[K,V] {
      import scala.collection.mutable.LinkedHashMap
      var map = new LinkedHashMap[K, V]()

      /* adds an element to the HaskMap */
      def add(key: K, value: V) {
        map.put(key, value)
      }

      /* removes the LRU element from the HaskMap */
      def removeEldest {
        if (!map.isEmpty) {
          map = map.drop(1)
        }
      }

      /* gets the value for the given key and moves it to the top of the HashMap */
      def get(key: K): Option[V] = {
        val value = map.remove(key)
        if (value != None) {
          map.put(key, value.get)
        }
        return value
      }
    }
+2
source

Source: https://habr.com/ru/post/1545127/


All Articles