I have an implementation of a Set in Scala. I want to create a Map whose key operations are backed by this Set implementation. Since we can get the keySet from a Map, can we construct a Map using a Set implementation?
Asked
Active
Viewed 59 times
0
-
2Does this answer your question? [Scala: How to create a Map\[K,V\] from a Set\[K\] and a function from K to V?](https://stackoverflow.com/questions/5582862/scala-how-to-create-a-mapk-v-from-a-setk-and-a-function-from-k-to-v) – AlleXyS Jul 19 '20 at 08:16
-
There are valid approaches to convert a Set to a Map but the keys of the Map won't be backed by the set. I want the uniqueness of the keys to be maintained by the logic of the set. Is this possible without a custom implementation of the Map? – CodeMan Jul 19 '20 at 08:41
-
2Genuine question: why would you want a `Map` backed by a `Set`? If it's to avoid constructing a new collection when calling `keySet`, are you aware that (at least in 2.13.x) the `Set` returned by `keySet` is lazy (any operation on a `Set` that doesn't require traversal doesn't force a traversal of the `Map`)? – Levi Ramsey Jul 19 '20 at 13:53
-
2The short answer is that a custom implementation is required, and the reason for this is that there isn't a `Set`-backed `Map` which doesn't either: A) have both a `Set` and something sufficient to implement a `Map` as backing (i.e. you didn't need the `Set` backing) or B) has to make a choice between supporting parts of the `Map` API on which most of the rest depend and being highly non-performant. – Levi Ramsey Jul 19 '20 at 13:56
-
1What is so important of backing the keys in the Set? What do you want to avoid when creating a new map? – Luis Miguel Mejía Suárez Jul 19 '20 at 14:20
-
Perhaps you want a `Set[(K, V)]` instead? – user Jul 19 '20 at 15:42