0

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?

Andrea
  • 47
  • 7

1 Answers1

0

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.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Isn't `mapValues` lazy and you are executing side effects each time you print values? – Oleg Pyzhcov Dec 04 '17 at 13:34
  • @OlegPyzhcov `mapValues` is lazy, and `foreach` is the one materializing the result. Added a comment and an alternative strict solution. Thanks for noticing. – Yuval Itzchakov Dec 04 '17 at 13:37
  • What data structure should i use? I will apply it to lists of hundreds of elements. I choose `LinkedHashMap` 'cause it uses a hash table. Also, isn't it possible to add the element at the head of each list? – Andrea Dec 04 '17 at 13:45
  • @YuvalItzchakov mapValues is not memoizing, IIRC, so if you print twice, you get side effects executed twice. Better just use `foreach` – Oleg Pyzhcov Dec 04 '17 at 13:48
  • @OlegPyzhcov It isn't. Better use `map` if the overall execution needs to happen immediately. – Yuval Itzchakov Dec 04 '17 at 13:51
  • @Andrea It is possible, use `lstBuffer.prepend(6)` instead. – Yuval Itzchakov Dec 04 '17 at 13:52
  • @YuvalItzchakov I just found out there is a mutable.HashTable class, but i can't see any example on the internet. Can you tell me how to even put keys and values into it? :( – Andrea Dec 04 '17 at 16:45
  • Why do you need to use `mutable.HashTable`? – Yuval Itzchakov Dec 04 '17 at 17:22
  • My purpose is to implement a hash table, with a constant time in research and delete operations @YuvalItzchakov – Andrea Dec 04 '17 at 17:31