qartal
qartal

Reputation: 2064

How to convert Map values to a set in scala

In a Map class of Scala, the keySet method returns the set of the Map keys. The collection of map values are not set (as two keys might refer to the same value, so it is a multi-set). The valuesIterator method of the Map class returns an iterator, which makes these values traversable, so it is possible to build the set of values of a Map as bellow:

val f=Map(1->10,2->15,3->20,4->20,6->20)
val it=f.valuesIterator
var valueSet=Set.empty[Int]
while (it.hasNext){
  valueSet=valueSet+it.next();
}

println(valueSet)  // this will print Set(10, 20, 15)

Question:

Is there any concise way to get the values of a map as a set?

Upvotes: 4

Views: 6611

Answers (2)

Brian
Brian

Reputation: 7316

Another solution just for giggles is to invert the map using swap and then grab the keyset

val myMap = Map(("A", 1), ("B", 2), ("C", 3))
myMap.map(_.swap).keySet

Upvotes: 1

Ben Reich
Ben Reich

Reputation: 16324

You're probably looking for the toSet method on TraversableOnce:

def toSet[B >: A]: immutable.Set[B]

Converts this traversable or iterator to a set. Note: will not terminate for infinite-sized collections.

returns a set containing all elements of this traversable or iterator.

You can use that together with the values or valuesIterator method on Map by doing map.values.toSet or map.valuesIterator.toSet.

You might also be interested in the Set.apply method that takes a variadic parameter, which can be invoked here as: Set(map.values.toList:_*).

If you ever do need to build a collection iteratively as you have done, you should familiarize yourself with the builder pattern, which allows you to only use a mutable data structure temporarily, and avoid stateful and error-prone vars. For example here you could do (Set.newBuilder ++= map.values).result.

Upvotes: 5

Related Questions