Map Class Example
Here's a quick look at how to use the Scala Map class, with a colllection of Map class examples.
The immutable Map class is in scope by default, so you can create an immutable map without an import, like this:
val states = Map("AL" -> "Alabama", "AK" -> "Alaska")
To create a mutable Map, import it first:
var states = scala.collection.mutable.Map("AL" -> "Alabama")
Adding, removing, and updating mutable Map elements
The following examples show how to add, remove, and update elements in a mutable Scala Map:
// create an empty map
var states = scala.collection.mutable.Map[String, String]() // create a map with initial elements
var states = scala.collection.mutable.Map("AL" -> "Alabama", "AK" -> "Alaska") // add elements with +=
states += ("AZ" -> "Arizona")
states += ("CO" -> "Colorado", "KY" -> "Kentucky") // remove elements with -=
states -= "KY"
states -= ("AZ", "CO") // update elements by reassigning them
states("AK") = "Alaska, The Big State"
Iterating over Scala maps
Once you have a Map, you can iterate over it using several different techniques. I prefer using the for loop (or for comprehension):
scala> val m1 = Map("fname" -> "Al", "lname" -> "Alexander")
scala> for ((k,v) <- m1) printf("key: %s, value: %s\n", k, v)
key: fname, value: Al
key: lname, value: Alexander
This page has some other Map and for loop examples, which I've reproduced here:
// version 1 (tuples)
m1 foreach (x => println (x._1 + "-->" + x._2)) // version 2 (foreach and case)
m1 foreach {case (key, value) => println (key + "-->" + value)}
You can choose whatever format you prefer.
A few more ways to iterate over a Scala Map
To demonstrate a more "real world" example of looping over a Scala Map, while I was working through some programming examples in the book,Programming Collective Intelligence, I decided to code them up in Scala.
To begin with, I defined my Scala Map like this:
val p1Ratings = Map("Lady in the Water"-> 3.0,
"Snakes on a Plane"-> 4.0,
"You, Me and Dupree"-> 3.5)
In my case, when I'm iterating over the Map I'm really just interested in the Map keys, so the cleanest way to loop over every Map element is like this:
p1Ratings.keys.foreach( (movie) =>
if (p2Ratings.contains(movie)) similarItems += (movie -> true)
)
While I chose that looping method in my code, I could also use the "tuples" approach, where movie is a Tuple, and I only use the first element of the Tuple, which happens to be my keys:
p1Ratings foreach ( (movie) =>
if (p2Ratings.contains(movie._1)) similarItems += (movie._1 -> true)
)
In that approach, I ignore the second element of each Tuple, because I don't need it. (Which is why I don't like this approach for this instance.)
In a similar approach, I loop over the Map as shown next, creating a field named rating1 which I again don't use because I don't need it:
for ((movie1, rating1) <- p1Ratings) {
if (p2Ratings.contains(movie1)) similarItems += (movie1 -> true)
}
These last two approaches will work better, and look a little more logical, if you need to access the key and value for each map element, but in my case, since I don't need to values, I'm using the first approach shown above.
Map Class Example的更多相关文章
- mapreduce中一个map多个输入路径
package duogemap; import java.io.IOException; import java.util.ArrayList; import java.util.List; imp ...
- .NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法
.NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法 0x00 为什么需要Map(MapWhen)扩展 如果业务逻辑比较简单的话,一条主管道就够了,确实用不到 ...
- Java基础Map接口+Collections工具类
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- Java基础Map接口+Collections
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- 多用多学之Java中的Set,List,Map
很长时间以来一直代码中用的比较多的数据列表主要是List,而且都是ArrayList,感觉有这个玩意就够了.ArrayList是用于实现动态数组的包装工具类,这样写代码的时候就可以拉进 ...
- Java版本:识别Json字符串并分隔成Map集合
前言: 最近又看了点Java的知识,于是想着把CYQ.Data V5迁移到Java版本. 过程发现坑很多,理论上看大部分很相似,实践上代码写起来发现大部分都要重新思考方案. 遇到的C#转Java的一些 ...
- MapReduce剖析笔记之八: Map输出数据的处理类MapOutputBuffer分析
在上一节我们分析了Child子进程启动,处理Map.Reduce任务的主要过程,但对于一些细节没有分析,这一节主要对MapOutputBuffer这个关键类进行分析. MapOutputBuffer顾 ...
- MapReduce剖析笔记之七:Child子进程处理Map和Reduce任务的主要流程
在上一节我们分析了TaskTracker如何对JobTracker分配过来的任务进行初始化,并创建各类JVM启动所需的信息,最终创建JVM的整个过程,本节我们继续来看,JVM启动后,执行的是Child ...
- MapReduce剖析笔记之五:Map与Reduce任务分配过程
在上一节分析了TaskTracker和JobTracker之间通过周期的心跳消息获取任务分配结果的过程.中间留了一个问题,就是任务到底是怎么分配的.任务的分配自然是由JobTracker做出来的,具体 ...
- MapReduce剖析笔记之三:Job的Map/Reduce Task初始化
上一节分析了Job由JobClient提交到JobTracker的流程,利用RPC机制,JobTracker接收到Job ID和Job所在HDFS的目录,够早了JobInProgress对象,丢入队列 ...
随机推荐
- MySQL优化小案例:连接数
错误代码:MySQL: ERROR 1040: Too many connections 经常会遇到这个错误,要么是业务增长,正常的访问量增多,要么是自己的max_connections设置的过小了 ...
- Android 如何将Canvas上绘制的内容保存成本地图片(转)
效果如下图所示 保存在sd卡上的文件为 手机上显示效果为: 1>>在Manifest文件中增加相应权限 <!-- 在SDCard中创建与删除文件权限 --> <uses- ...
- uniq命令 (转)
uniq命令可以去除排序过的文件中的重复行,因此uniq经常和sort合用.也就是说,为了使uniq起作用,所有的重复行必须是相邻的. uniq语法 [root@www ~]# uniq [-icu] ...
- 恭喜您成为2014年度Microsoft MVP!
- mysql字符集和字符排序
mysql的字符集和字符序: 字符序:字符序(Collation)是指在同一字符集内字符之间的比较规则 一个字符序唯一对应一种字符集,但一个字符集可以对应多种字符序,其中有一个是默认字符序 ...
- js setAttribute removeAttribute
<input type="button" value="生效" style="font-size:111px"/> <sc ...
- 【LeetCode】107. Binary Tree Level Order Traversal II (2 solutions)
Binary Tree Level Order Traversal II Given a binary tree, return the bottom-up level order traversal ...
- 如何理解并学习javascript中的面向对象(OOP) [转]
如果你想让你的javascript代码变得更加优美,性能更加卓越.或者,你想像jQuery的作者一样,写出属于自己优秀的类库(哪怕是基于 jquery的插件).那么,你请务必要学习javascript ...
- xcode 在哪里新建category、protocol等文件
1.和以前新建新文件一样.2.当然选IOS啦,不过OS X也有这个选项,然后Objctive-C File. 3.在File Type里选就OK啦.
- Python abs() 函数
描述 abs() 函数返回数字的绝对值. 语法 以下是 abs() 方法的语法: abs( x ) 参数 x -- 数值表达式,可以是整数,浮点数,复数. 返回值 函数返回 x(数字)的绝对值,如果参 ...