Reputation: 809
Assume we have a standard scala.collection.immutable.Map
. Is the following assertion true? Does it hold for all types of maps?
I have inspected the source code of MapLike
. It seems .keys
and .values
use the same iterator, but I am not sure of the exact behavior of such iterator.
val a = Map(....)
val keys = a.keys.toSeq
val values = a.values.toSeq
val seq = a.toSeq
assert(seq == keys.zip(values))
Upvotes: 0
Views: 66
Reputation: 27421
This may be true for the current implementation of these collections but you cannot assume that it will be true in the general case. If you want the order of the keys to be guaranteed, use ListMap
.
If you need the keys and values as separate lists while guaranteeing that the elements in each list correspond, do this:
val (keys, values) = a.unzip
Upvotes: 4