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. PHP中静态方法(static)与非静态方法的使用及区别

    今天再次学习这个内容,总是糊里糊涂的,想弄明白!!! static关键字用来修饰属性.方法,称这些属性.方法为静态属性.静态方法.static关键字声明一个属性或方法是和类相关的,而不是和类的某个特定 ...

  2. ios 的 desciption

    前段时间,终于将 ipa 文件打包完毕,上传appStore ,最后被打回,是因为 敏感的调用设备功能没有写描述. 有两种解决方式: A.直接修改 info.plist 文件 1.设置启动图标(CFB ...

  3. SQL 2008 R2数据库变为REPLICATION,日志不断增长并且不能截断和收缩的解决方式

     执行环境:windows server2003,sql server2008 R2,数据库上布置CDC   用户反应系统报错是日志已满,系统不能执行. 查看日志文件时.发现日志文件已经达到15G ...

  4. SettingsJDK

      迁移时间:2017年5月20日23:38:40 Author:Marydon 1.双击安装,更改安装路径为D:\ProgramFiles\Java\jdk1.7.0_55: 注意事项: 1.1 将 ...

  5. Python之L.pop()和del L[i]

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #Python之L.pop()和del L[i] #http://python.jobbole.com/826 ...

  6. JUC-Callable

    实现线程的方式有四种: 1,实现runnable接口: 2,继承Thread. 3,也就是本节的Callable接口. 4,使用线程池. 区别: 实现Callable接口的方式,相较于实现Runnab ...

  7. yum插件yum-fastestmirror

    yum多个mirror自动选择速度最快的mirror,yum-fastestmirror插件,它会自动选择最快的mirror 配置文件: /etc/yum/pluginconf.d/fastestmi ...

  8. 微信小程序--搜索关键词高亮

    代码地址如下:http://www.demodashi.com/demo/14249.html 一.前期准备工作 软件环境:微信开发者工具 官方下载地址:https://mp.weixin.qq.co ...

  9. 封装UIlabel 辨别用户名 ,话题 ,链接,电话,高亮文字等

    概述 对UIlabel进行封装 用于辨别用户名 ,话题 ,链接,电话,高亮文字等,链接跳转网页,电话点击拨打电话,完美封装UIlabel,适合绝大多数需求 详细 代码下载:http://www.dem ...

  10. WeUI 是由微信官方设计团队专为微信移动 Web 应用设计的 UI 库

    WeUI 是由微信官方设计团队专为微信移动 Web 应用设计的 UI 库. WeUI 是一套同微信原生视觉体验一致的基础样式库,为微信 Web 开发量身设计,可以令用户的使用感知更加统一.包含butt ...