Why does my card claim that it does not have keys after adding keys?

I have an Int-> Queue card, and I add one entry to the queue at a time. At the end of the process, I need to iterate over the keys and values ​​(because I want to convert the queues to arrays), but scala says there are no keys / values ​​on the map. Some simplified codes are provided below for illustration. What's going on here? The result m (4) below is also puzzling.

import scala.collection.mutable.Queue

val m = Map[Int, Queue[Int]]().withDefaultValue(Queue[Int]())

m(1) += 10
res25: scala.collection.mutable.Queue[Int] = Queue(10)

m(1) += 10
res26: scala.collection.mutable.Queue[Int] = Queue(10, 10)

m(1)
res35: scala.collection.mutable.Queue[Int] = Queue(10, 10)

m(4)
res37: scala.collection.mutable.Queue[Int] = Queue(10, 10)

m.keys
res28: Iterable[Int] = Set()

m
res36: scala.collection.immutable.Map[Int,scala.collection.mutable.Queue[Int]] = Map()

Using scala 2.10.3.

-2
source share
3 answers

You never add anything to the map. You get the changed queue that you set as the default and change it.

+2
source

, , Queue , "".

import scala.collection.mutable.Queue
val mutablemap = scala.collection.mutable.Map[Int, Queue[Int]]()

mutablemap(9) = mutablemap.lift(9).fold(Queue(99))(_ += 99)
mutablemap(2) = mutablemap.lift(2).fold(Queue(22))(_ += 22)
mutablemap(9) = mutablemap.lift(9).fold(Queue(19))(_ += 19)
mutablemap(2) = mutablemap.lift(2).fold(Queue(12))(_ += 12)

mutablemap(9)  // res0: scala.collection.mutable.Queue[Int] = Queue(99, 19)
mutablemap(2)  // res1: scala.collection.mutable.Queue[Int] = Queue(22, 12)

.

import scala.collection.mutable.Queue
val mutablemap = 
  scala.collection.mutable.Map[Int, Queue[Int]]().withDefault(_ => Queue[Int]())

mutablemap(3) = mutablemap(3) += 37
mutablemap(3) = mutablemap(3) += 45
mutablemap(6) = mutablemap(6) += 60
mutablemap(6) = mutablemap(6) += 62

mutablemap(3)  // res0: scala.collection.mutable.Queue[Int] = Queue(37, 45)
mutablemap(6)  // res1: scala.collection.mutable.Queue[Int] = Queue(60, 62)
+1

puhlen:

-, . -, withDefaultValue, -, ( ).

val mutablemap = scala.collection.mutable.Map[Int, Queue[Int]]()

- , ( -, ):

if (mutablemap.contains(key)) {
    // mutate the existing Queue
    mutablemap(key) += new_value
} else {
    // key was not in map; start a new Queue
    mutablemap += key -> Queue[Int](first_value)
}
0

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


All Articles