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的更多相关文章

  1. mapreduce中一个map多个输入路径

    package duogemap; import java.io.IOException; import java.util.ArrayList; import java.util.List; imp ...

  2. .NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法

    .NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法 0x00 为什么需要Map(MapWhen)扩展 如果业务逻辑比较简单的话,一条主管道就够了,确实用不到 ...

  3. Java基础Map接口+Collections工具类

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  4. Java基础Map接口+Collections

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  5. 多用多学之Java中的Set,List,Map

            很长时间以来一直代码中用的比较多的数据列表主要是List,而且都是ArrayList,感觉有这个玩意就够了.ArrayList是用于实现动态数组的包装工具类,这样写代码的时候就可以拉进 ...

  6. Java版本:识别Json字符串并分隔成Map集合

    前言: 最近又看了点Java的知识,于是想着把CYQ.Data V5迁移到Java版本. 过程发现坑很多,理论上看大部分很相似,实践上代码写起来发现大部分都要重新思考方案. 遇到的C#转Java的一些 ...

  7. MapReduce剖析笔记之八: Map输出数据的处理类MapOutputBuffer分析

    在上一节我们分析了Child子进程启动,处理Map.Reduce任务的主要过程,但对于一些细节没有分析,这一节主要对MapOutputBuffer这个关键类进行分析. MapOutputBuffer顾 ...

  8. MapReduce剖析笔记之七:Child子进程处理Map和Reduce任务的主要流程

    在上一节我们分析了TaskTracker如何对JobTracker分配过来的任务进行初始化,并创建各类JVM启动所需的信息,最终创建JVM的整个过程,本节我们继续来看,JVM启动后,执行的是Child ...

  9. MapReduce剖析笔记之五:Map与Reduce任务分配过程

    在上一节分析了TaskTracker和JobTracker之间通过周期的心跳消息获取任务分配结果的过程.中间留了一个问题,就是任务到底是怎么分配的.任务的分配自然是由JobTracker做出来的,具体 ...

  10. MapReduce剖析笔记之三:Job的Map/Reduce Task初始化

    上一节分析了Job由JobClient提交到JobTracker的流程,利用RPC机制,JobTracker接收到Job ID和Job所在HDFS的目录,够早了JobInProgress对象,丢入队列 ...

随机推荐

  1. Jsp之神笔记

    JSP笔记 Tomcatserver port: port就是指的某一个程序网络入口,Tomcat的初始化port为:8080: port的个数:256*256=65536个: 一般常见协议的缺省po ...

  2. eclipse git提交代码

    1.安装git 2.安装好后,进行,一个简单配置,填入我们的用户名和邮箱 >>Preferences>Team>Git>Configuration 设置自定义仓库 3.登 ...

  3. windows命令行设置IP与DNS

    用dos命令修改IP等本地连接属性 平时我们改IP通常都在是窗口界面本地连接直接修改, 那在命令行也可以设置IP地址?当然可以,这里要用到netsh命令 .点击“开始”->“运行”,输入“cmd ...

  4. Swift教程_swift常见问题(0005)_完美解决Cannot override &#39;dealloc&#39;异常

    Swift教程_swift常见问题(0001)_CoreData: warning: Unable to load class named 'xxx' for entity 'xxx' Swift教程 ...

  5. python之函数用法staticmethod

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法staticmethod #http://www.cnblogs.com/hongfe ...

  6. 保护HTTP的安全

    #如果没有严格的限制访问的权限,公司放在服务器上的重要文档就存在隐患,web需要有一些安全的http形式: #安全方法: #基本认证.摘要认证.报文完整性检查都是一些轻量级的方法,但还不够强大,下面介 ...

  7. 关联更新SQL语句

    update F_A_Info  set level=b.level from  F_A_Info a,F_A_Info_QUAN b where a.id=b.id

  8. HDUOJ----More is better(并查集)

    More is better Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 327680/102400 K (Java/Others) ...

  9. bootstrap table 插件 搜索

    以前用过easyui datagrid 每次搜索的时候调用datagrid构造方法 重新获取数据, 发现bootstrap-table 插件不行,只需要初始化一次, 以后每次搜索时,直接调用refre ...

  10. -no-xrender will disable the qtwebkit

    -no-xrender will disable the qtwebkit         apt-get install libxrender-dev 来自为知笔记(Wiz)