Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an immutable map/set from a seq?

I am try to construct immutable Sets/Maps from a Seq. I am currently doing the following:

val input: Seq[(String, Object)] = //..... Map[String, Object]() ++ input 

and for sets

val input: Seq[String] = //..... Set[String]() ++ input 

Which seems a little convoluted, is there a better way?

like image 406
Michael Barker Avatar asked Jan 01 '10 13:01

Michael Barker


People also ask

Is seq immutable?

Seq is immutable — Once a Seq is created, it cannot be changed, appended to, rearranged or otherwise modified.

Is seq immutable in Scala?

Seq which represents sequences that are guaranteed immutable.

How can we convert mutable to immutable?

If you just want a mutable HashMap , you can just use x. toMap in 2.8 or collection. immutable. Map(x.


2 Answers

In Scala 2.8:

Welcome to Scala version 2.8.0.r20327-b20091230020149 (Java HotSpot(TM) Client VM, Java 1.6. Type in expressions to have them evaluated. Type :help for more information.  scala> val seq: Seq[(String,Object)] = ("a","A")::("b","B")::Nil seq: Seq[(String, java.lang.Object)] = List((a,A), (b,B))  scala> val map = Map(seq: _*) map: scala.collection.immutable.Map[String,java.lang.Object] = Map(a -> A, b -> B)  scala> val set = Set(seq: _*) set: scala.collection.immutable.Set[(String, java.lang.Object)] = Set((a,A), (b,B))  scala> 

Edit 2010.1.12

I find that there is a more simple way to create set.

scala> val seq: Seq[(String,Object)] = ("a","A")::("b","B")::Nil seq: Seq[(String, java.lang.Object)] = List((a,A), (b,B))  scala> val set = seq.toSet set: scala.collection.immutable.Set[(String, java.lang.Object)] = Set((a,A), (b,B)) 
like image 96
Eastsun Avatar answered Oct 04 '22 06:10

Eastsun


To convert a Seq to a Map, simply call toMap on the Seq. Note that the elements of the Seq must be Tuple2 ie. (X,Y) or (X->Y)

scala> val seq: Seq[(String,String)] = ("A","a")::("B","b")::("C","c")::Nil seq: Seq[(java.lang.String, java.lang.String)] = List((A,a), (B,b), (C,c))  scala> seq.toMap res0: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map((A,a), (B,b), (C,c)) 

To convert a Seq to a Set, simply call toSet on the Seq.

scala> val seq: Seq[String] = "a"::"b"::"c"::Nil seq: Seq[java.lang.String] = List(a, b, c)  scala> seq.toSet res1: scala.collection.immutable.Set[java.lang.String] = Set(a, b, c) 
like image 39
Chris Stivers Avatar answered Oct 04 '22 04:10

Chris Stivers