scalalinkedhashmaplistbuffer

Removing elements from a map of type (Int, ListBuffer(Int))


I have LinkedHashMaps of type:

val map1 = LinkedHashMap(1 -> 1, 2 -> (1,2), 3 -> (1,2,3)) val map2 = LinkedHashMap(2 -> 2, 3 -> (2,3), 5 -> (2,3,5))

where the integers are nodes's ids of a graph, and the list is the path to that node. I want to implement the case of deleting a node. Suppose I want to delete node 3, I have to do two actions: remove the element with key = 3 in every map, remove the elements which have 3 in their list. How to do it in scala?


Solution

  • If you define you map like you have,

    val map1 = LinkedHashMap(1 -> 1, 2 -> (1,2), 3 -> (1,2,3))
    

    You do not have key: Int and value: List[Int] but you have key: Int and values: Any.

    scala> val map1 = LinkedHashMap(1 -> 1, 2 -> (1,2), 3 -> (1,2,3))
    // map1: scala.collection.mutable.LinkedHashMap[Int,Any] = Map(1 -> 1, 2 -> (1,2), 3 -> (1,2,3))
    

    To match your requirement, you should define your map like following,

    scala> val map1 = LinkedHashMap(1 -> List(1), 2 -> List(1,2), 3 -> List(1,2,3))
    // map1: scala.collection.mutable.LinkedHashMap[Int,List[Int]] = Map(1 -> List(1), 2 -> List(1, 2), 3 -> List(1, 2, 3))
    

    Now, if you want to delete a node 3,

    scala> val map2 = map1.filter({
         |   case (key, list) => key != 3 && !list.contains(3)
         | })
    // map2: scala.collection.mutable.LinkedHashMap[Int,List[Int]] = Map(1 -> List(1), 2 -> List(1, 2))