scala学习之map和tuple
2015-08-06 18:13
417 查看
Map
//不可变的Map val scores = Map("Alice" -> 3, "lucy" -> 6, "Lily" -> 9) //可变的 scala.collection.mutable.Map("Alice" -> 3, "lucy" -> 6, "Lily" -> 9) var map = new mutable.HashMap[String, Int] map += ("cindy" -> 5) println(map) //操作Map println(scores("Alice")) //如果映射中不包含 该键 会抛出异常 //检查map中是否含有某个键 可以使用contains 方法 val score = if (scores.contains("lucy")) scores("lucy") else 0 //或者 scores.getOrElse("lucy", 0) map("cindy") = 10 //更新cindy的值 map("lilei") = 8 //增加新的映射 //也可以这样 map +=("Bob" -> 5, "Fred" -> 7) map -= "lilei" //移除键值对 /** * 不能update不可以变的map,但是可以得到一个新的map */ val newScores = scores +("Bob" -> 5, "Fred" -> 7) //也可以如此 var scoreses = Map("Alice" -> 3, "lucy" -> 6, "Lily" -> 9) scoreses = scoreses +("Bob" -> 5, "Fred" -> 7) //从不可变Map中移除值 scoreses = scoreses - "lucy" //迭代 for ((name, num) <- scoreses) println("name :" + name + " socre:" + num) //返回key值set集合 println(scoreses.keySet) //获取所有的value for (v <- scoreses.values) println(v) //反转map var reverSocres = for ((name, num) <- scoreses) yield (num, name) println(reverSocres) //不可变的TreeMap SortedMap("Alice" -> 3, "lucy" -> 6, "Lily" -> 9)tuple:
//元组 val t = (1,3.14,"scala") println(t._1) //访问元组 从1开始 val (first,second,third) = t //依次对first,second,third为1,3.14,"scala" val (f,s,_) = t //如果不需要全部的值可以如此写 //zip 很像python中的zip函数 val symbols = Array("<","-",">") val counts = Array(3,6,3) val pairs = symbols.zip(counts) for ((s,n) <- pairs) Console.print(s * n) //打印<<<------>>>
相关文章推荐
- 使用Dropbox+Justwriting+Markdown建立个人博客
- Mysql数据库设计
- chain
- 微信支付V3版本的那些事
- TinyXML:一个优秀的C++ XML解析器
- 反转单向链表
- JPA入门例子(采用JPA的hibernate实现版本)
- 使用GCD
- 在一个文件中有10G个整数,乱序排列,要求找出中位数
- QT学习笔记(一)——ui的认识
- Linux通过samba访问windows文件
- Codeforces B - Berland National Library
- Codeforces Gym 100342C Problem C. Painting Cottages 暴力
- HBuilder 获取通讯录
- iOS学习(其他小控件的使用)
- 我是菜鸟:MapReduce编程模型
- Server redirected too many times
- 线型表的C++实现
- 解决读取bitmap内存溢出问题
- hdu5353Average