val f = Map("foo" -> 1, "bar" -> 2)
val f=scala.collection.mutable.Map("foo"->2,"bar"->3)
val f= new scala.collection.mutable.HashMap[String,Int]
->
是用来创建对偶的。"fooo"->3
的值是 (String, Int) = (fooo,3)
val a = f("foo")
如果不存在键就抛异常contains
方法: val a=if (f.contains("baz")) f("baz") else 0
或者用糖 val a=f.getOrElse("baz",0)
get
方法返回 Option
对象f("bar") = 10
或者用 +=
符号更新 f += ("a"->1,"ab"->2)
-=
移除某个键 f -= "a"
+
-
符号如你所愿for ((k,v)<-映射)
遍历keySet
和 values
方法可以获得键和值for ((k,v)<-map) yield(v,k)
翻转,吊吊的scala.collection.immutable.SortedMap
的实现是树形映射,有序,但是不可变。如果想要可变的树形映射,请用Java中的 TreeMap
scala.collection.mutable.LinkedHashMap
import scala.collection.JavaConversions.mapAsScalaMap
转换 import scala.collection.JavaConversions.propertiesAsScalaMap
可以将 java.util.properties
转到 Map[String,String]
反之亦有相关类库val t = (1,3.14,"abc")
创建元组_1
_2
_3
方法访问元组的元素。但通常使用模式匹配来赋值 val (first, second, third) = t
val symbols = Array("<","-",">"); val counts = Array(2, 10, 2); val pairs = symbols.zip(counts)
然后就可以对齐进行一起操作了 for ((s,n)<-pairs) print(s*n)
toMap
方法可以将对偶的集合转成映射 pairs.toMap
练习
练习
val m = Map("shoe"->223.3, "shirt"->107.1,"coat"->320.0); val mAfter = for((name,price) <- m) yield (name,price*0.9)
val words = new scala.collection.mutable.HashMap[String,Int]; val in = new java.util.Scanner(new java.io.File("myfile.txt")); while(in.hasNext()) {val w=in.next();words(w)=words.getOrElse(w,0)+1}; for((w,n)<-words) printf("%s\t%d\n",w,n)
var words=Map[String,Int](); val in = new java.util.Scanner(new java.io.File("myfile.txt")); while(in.hasNext()) {val w=in.next();words = words + (w -> (words.getOrElse(w,0)+1)) }; for((w,n)<-words) printf("%s\t%d\n",w,n)
var words=scala.collection.immutable.SortedMap[String,Int](); val in = new java.util.Scanner(new java.io.File("myfile.txt")); while(in.hasNext()) {val w=in.next();words = words + (w -> (words.getOrElse(w,0)+1)) }; for((w,n)<-words) printf("%s\t%d\n",w,n)
import scala.collection.JavaConversions.mapAsScalaMap; var words=new java.util.TreeMap[String,Int]; val in = new java.util.Scanner(new java.io.File("myfile.txt")); while(in.hasNext()) {val w=in.next();words(w)=words.getOrElse(w,0)+1}; for((w,n)<-words) printf("%s\t%d\n",w,n)
val m = new scala.collection.mutable.LinkedHashMap[String,Int](); m("Monday")=java.util.Calendar.MONDAY; m("Tuesday")=java.util.Calendar.TUESDAY;m("Wednesday")=java.util.Calendar.WEDNESDAY;m("Thursday")=java.util.Calendar.THURSDAY;m("Friday")=java.util.Calendar.FRIDAY;m("Saturday")=java.util.Calendar.SATURDAY;m("Sunday")=java.util.Calendar.SUNDAY;
import scala.collection.JavaConversions.mapAsScalaMap; import scala.collection.JavaConversions.asScalaSet; val ps = java.lang.System.getProperties(); val len = (s:Object) => s.toString.length; val maxlen = len(ps.keySet.maxBy(len)); for ((o,v)<-ps) printf("%-"+(maxlen+1)+"s| %s\n", o, v)
def minmax(values: Array[Int]) = (values.min, values.max)
def lteqgt(values: Array[Int], v: Int) = (values.count(_<v), values.count(_==v), values.count(_>v))