scalalistlinkedhashmaplistbuffermutablemap

How to update every value of the keyset in a LinkedHashMap in Scala, having a LinkedHashMap[Int, ListBuffer[Int]]?


I have a LinkedHashMap of type:

var map: LinkedHashMap[Int, ListBuffer[Int]] = ((1 -> (2, 1)), (2 -> 2), (3 -> (5, 3)))

I want to add an element to every list of every key, let's say i want to add "6" in order to have:

((1 -> (6, 2, 1)), (2 -> (6, 2)), (3 -> (6, 5, 3)))

How do i do this?


Solution

  • Like this:

    val map: mutable.LinkedHashMap[Int, ListBuffer[Int]] =
      mutable.LinkedHashMap(1 -> ListBuffer(2, 1),
                            2 -> ListBuffer(2, 2),
                            3 -> ListBuffer(5, 3))
    
    val res = map.mapValues(lstBuffer => lstBuffer += 6)
    println(res)
    

    Yields:

    Map(1 -> ListBuffer(2, 1, 6), 2 -> ListBuffer(2, 2, 6), 3 -> ListBuffer(5, 3, 6))
    

    Note that mapValues is lazy and won't execute unless materialized. If we want to make this strict and execute immediately, we can use map:

    val res = map.map { case (_, lstBuffer) => lstBuffer += 6 }
    

    If you want to prepend, use .prepend instead (which returns Unit and is side effecting on the current Map instance):

    map.foreach { case (_, lstBuffer) => lstBuffer.prepend(6) }
    

    I want to note that usually, if you want to iterate the entire Map[K, V] sequentially, it's a sign you're using the wrong data structure. Although without more information I can't really establish a basis for that hypothesis.