scala - An efficient structure in which to keep a hash key and a collection of values -
i developing stateful application. states need data structure has hash-key , collection of values related key.
the collection should efficient , occupy least amount of memory possible. collection should mutable: items need removed or added.
is there such collection in scala?
the basic structure you're looking map nested collection:
map[k, set[v]]
normally, considered best practice use immutable values:
val first_state: map[string, set[string]] = map("a key" -> set("alpha", "omega")) val second_state = first_state + ("another key" -> set("theta", "iota")) val third_state = second_state + ("another key" -> set("kappa"))
the above results in following values:
first_state: map[string,set[string]] = map(a key -> set(alpha, omega)) second_state: scala.collection.immutable.map[string,set[string]] = map(a key -> set(alpha, omega), key -> set(theta, iota)) third_state: scala.collection.immutable.map[string,set[string]] = map(a key -> set(alpha, omega), key -> set(kappa))
we can see third state you'd looking in situation, , don't need mutable state you're trying do. this post shows number of examples of how manipulate immutable maps, if need more.
note scala tries not copy elements if doesn't have to. thus, while seems getting first_state
third_state
involves 2 complete copies, under hood not. unless have specific , measured performance problem, should tend towards immutable state (in order better ensure correctness). given current question there nothing stated suggests need mutable state.
Comments
Post a Comment