Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most succinct Scala way to reverse a Map?

What is the most succinct Scala way to reverse a Map? The Map may contain non-unique values.

EDIT:

The reversal of Map[A, B] should give Map[B, Set[A]] (or a MultiMap, that would be even better).

like image 516
missingfaktor Avatar asked Sep 09 '10 17:09

missingfaktor


People also ask

What is mutable Map in Scala?

In Scala, there are two kinds of maps: Mutable and Immutable. A mutable map object's value can be changed, while immutable maps do not allow the values associated with keys to be changed. Scala uses immutable maps by default. You can import scala. collection.

Is Scala Map a HashMap?

HashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map.

What is the Map type in the Scala?

By default Scala uses immutable Map.

Can maps have duplicate keys Scala?

Scala Map is a collection of Key-value pair. A map cannot have duplicate keys but different keys can have same values i.e keys are unique whereas values can be duplicate.


1 Answers

If you can lose duplicate keys:

scala> val map = Map(1->"one", 2->"two", -2->"two")
map: scala.collection.immutable.Map[Int,java.lang.String] = Map((1,one), (2,two), (-2,two))

scala> map.map(_ swap)
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map((one,1), (two,-2))

If you don't want access as a multimap, just a map to sets, then:

scala> map.groupBy(_._2).mapValues(_.keys.toSet)
res1: scala.collection.immutable.Map[
  java.lang.String,scala.collection.immutable.Set[Int]
] = Map((one,Set(1)), (two,Set(2, -2)))

If you insist on getting a MultiMap, then:

scala> import scala.collection.mutable.{HashMap, Set, MultiMap}
scala> ( (new HashMap[String,Set[Int]] with MultiMap[String,Int]) ++=
     |          map.groupBy(_._2).mapValues(Set[Int]() ++= _.keys) )
res2: scala.collection.mutable.HashMap[String,scala.collection.mutable.Set[Int]]
with scala.collection.mutable.MultiMap[String,Int] = Map((one,Set(1)), (two,Set(-2, 2)))
like image 55
Rex Kerr Avatar answered Oct 20 '22 22:10

Rex Kerr