Map, Map and flatMap in Scala

CUDA编译踩坑实录:如何正确设置-gencode参数适配你的GPU算力 本文深入解析CUDA编译中-gencode参数的核心原理与实战配置,帮助开发者解决常见的'Unsupported gpu architecture'错误。通过厘清虚拟架构与真实架构的区别,并提供多版本兼容的CMake配置方案,确保编译出的代码能精准适配不同GPU算力,兼顾性能与广泛兼容性。 阅读详情

One of the things I like about Scala is it’s collections framework. As a non CS graduate I only very lightly covered functional programming at university and I’d never come across it until Scala. One the benefits of Scala is that the functional programming concepts can be introduced slowly to the programmer. One of the first places you’ll start to use functional constructs is with the collections framework.

Chances are your first collection will be a list of items and we might want to apply a function to each item in the list in some way.

Map works by applying a function to each element in the list.

scala> val l = List(1,2,3,4,5)

scala> l.map( x => x*2 )
res60: List[Int] = List(2, 4, 6, 8, 10)

So there are some occasions where you want to return a sequence or list from the function, for example an Option

scala> def f(x: Int) = if (x > 2) Some(x) else None

scala> l.map(x => f(x))
res63: List[Option[Int]] = List(None, None, Some(3), Some(4), Some(5))

flatMap works applying a function that returns a sequence for each element in the list, and flattening the results into the original list. This is easier to show than to explain:

scala> def g(v:Int) = List(v-1, v, v+1)
g: (v: Int)List[Int]

scala> l.map(x => g(x))
res64: List[List[Int]] = List(List(0, 1, 2), List(1, 2, 3), List(2, 3, 4), List(3, 4, 5), List(4, 5, 6))

scala> l.flatMap(x => g(x))
res65: List[Int] = List(0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6)

This comes in really useful with the built in Option class because an option can be considered a sequence that is either empty or has 1 item.

scala> l.map(x => f(x))
res66: List[Option[Int]] = List(None, None, Some(3), Some(4), Some(5))

scala> l.flatMap(x => f(x))
res67: List[Int] = List(3, 4, 5)

So with that all covered, lets look at how you can apply those concepts to a Map. Now a map can be implemented a number of different ways, but regardless of how it is implemented it can be thought of as a sequence of Tuples, where a tuple is a pair of items, the key and the value.

scala> val m = Map(1 -> 2, 2 -> 4, 3 -> 6)
m: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 2 -> 4, 3 -> 6)

scala> m.toList
res69: List[(Int, Int)] = List((1,2), (2,4), (3,6))

We can access a tuple by accessing the inner variables _1 and _2

scala> val t = (1,2)
t: (Int, Int) = (1,2)

scala> t._1
res70: Int = 1

scala> t._2
res71: Int = 2

So we want to think about using map and flatMap on our Map, but because of the way a map works it often doesn’t make quite the same sense, we probably don’t want to apply a function to the tuple, but to the value side of the tuple, leaving the key as is, so for example we might want to double all the values. Map provides us with a function to do exactly that.

scala> m.mapValues(v => v*2)
res73: scala.collection.immutable.Map[Int,Int] = Map(1 -> 4, 2 -> 8, 3 -> 12)

scala> m.mapValues(v => f(v))
res74: scala.collection.immutable.Map[Int,Option[Int]] = Map(1 -> None, 2 -> Some(4), 3 -> Some(6))

But in my case I wanted to do something more like flat map in this case, I want a map to come out that misses out the key 1 because it’s value is None. flatMap doesn’t work on maps like mapValues, it get’s passed the tuple and if it returns a List single items you’ll get a list back, but if you return a tuple you’ll get a Map back.

scala> m.flatMap(e => List(e._2))
res85: scala.collection.immutable.Iterable[Int] = List(2, 4, 6)

scala> m.flatMap(e => List(e))
res86: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 2 -> 4, 3 -> 6)

Ok so we are pretty close to using options with flatMap, we need to filter out our None’s, we can do returning a list with just e => f(e._2) and we’ll get the list of values without the None’s, but that isn’t really what I want. What I need to do is return an Option containing a tuple. So here’s our updated function:

scala> def h(k:Int, v:Int) = if (v > 2) Some(k->v) else None
h: (k: Int, v: Int)Option[(Int, Int)]

and here’s how we might call it:

scala> m.flatMap ( e => h(e._1,e._2) )
res109: scala.collection.immutable.Map[Int,Int] = Map(2 -> 4, 3 -> 6)

but this is pretty ugly, all those _1 and _2’s make me sad. If only there was a nice way of unapplying the tuple into variables. Given that this works in python and in a number of places in scala I thought this code should work:

scala> m.flatMap ( (k,v) => h(k,v) )
:10: error: wrong number of parameters; expected = 1

I spent way too long today looking at this (in 5 minute chunks broken by meetings to be fair), before I gave in and asked a coworker what the hell I was missing. The answer is seems is that an unapply is normally only executed in a PartialFunction, which in scala is most easily defined as a case statement. So this is the code that works as expected:

scala> m.flatMap { case (k,v) => h(k,v) }
res108: scala.collection.immutable.Map[Int,Int] = Map(2 -> 4, 3 -> 6)

Note that we switch to using curly braces, indicating a function block rather than parameters, and the function is a case statement. This means that the function block we pass to flatMap is a partialFunction that is only invoked for items that match the case statement, and in the case statement the unapply method on tuple is called to extract the contents of the tuple into the variables. This form of variable extraction is very common, and you’ll see it used a lot.

There is of course another way of writing that code that doesn’t use flatMap. Since what we are doing is removing all members of the map that don’t match a predicate, this is a use for the filter method:

scala> m.filter( e => f(e._2) != None )
res114: scala.collection.immutable.Map[Int,Int] = Map(2 -> 4, 3 -> 6)

scala> m.filter { case (k,v) => f(v) != None }
res115: scala.collection.immutable.Map[Int,Int] = Map(2 -> 4, 3 -> 6)

scala> m.filter { case (k,v) => f(v).isDefined }
res116: scala.collection.immutable.Map[Int,Int] = Map(2 -> 4, 3 -> 6)
Keil5保姆级安装指南:从破解到STM32开发环境配置(附常见错误解决方案) 本文提供Keil5从安装到STM32开发环境配置的完整指南,包含破解步骤、常见错误解决方案及多芯片支持配置。详细讲解环境预检、核心安装、许可证管理及高效开发环境设置,帮助开发者快速搭建嵌入式开发平台。特别针对安装和卸载过程中的关键问题提供专业解决方案。 阅读详情

相关推荐

Unity-Chan Toon Shader卡通渲染学习

2.0 (UTS2)是一款用于图像和视频的卡通着色器,旨在满足从事卡通着色 3DCG 动画的创作者的需求。二、从0-1复刻UTS21.漫反射UTS2的漫反射部分主要有三个层组成,分别是基本颜色、第一阴影色和第二阴影色,分别对应着美术理论中的白、灰、黑。

qq_63133691的博客 2539

Scala中List的map和flatMap的区别

写在前面:map方法的核心是映射每个元素并进行操作后将结果保存为一个列表,最后汇集所有的结果列表作为列表元素形成一个新的列表 flatMap房的核心是先映射每个元素,然后进行操作,然后进行扁平化处理,最后汇集所有进行扁平化处理的结果集形成一个新的列表(扁平化:简而言之就是去除所有的修饰) 1.map的例子(摘自Scala编程) 2.map的例子(...

qq_41733481的博客 4278

RAG开源框架深度评测:从RAGFlow到Dify的实战选型指南

本文深度评测了主流RAG开源框架(RAGFlow、Dify、WeKnora)的核心能力与实战表现,提供企业级选型指南。重点对比了文档解析、检索性能和生产部署等关键指标,揭示RAGFlow在复杂文档处理、Dify在低代码开发、WeKnora在腾讯生态集成的差异化优势,并给出技术选型决策树与成本优化方案。

weixin_29294597的博客 826

Scala比较理解map、flatMap

写在前面:首先问几个问题,如果以下问题大家都能轻松的说明白,那么说明你对这几种方法已经熟练掌握了。如果对这些问题,你还有疑问,那么我希望通过这篇文章能让你不再有疑问。 1、Scala中map、flatMap的区别是什么? 2、map/flatMap 和filter/where在处理数据上的区别又是什么? 3、map和UDF在处理数据上的区别是什么?map(函数)的方法是否等同于UDF?如果等同,那么UDF的优势是什么,适用场景是什么? 4、flatMap() 和UDTF有什么区别? 和SQL中的..

Toby的博客 1690

ADS版图优化中的参数化设计技巧

本文详细介绍了在ADS中进行射频电路版图参数化设计的核心技巧。通过将版图关键尺寸定义为变量,并与电磁仿真及优化器联动,实现从手动修改到自动迭代的转变,极大提升了PA、LNA等电路的设计与优化效率。文章以阶梯阻抗变换器为例,阐述了变量创建、绑定及协同仿真的完整流程,并提供了避免网格冲突、变量混乱等常见问题的实用指南。

weixin_29296241的博客 405

新建菜单Office被替换为腾讯文档 - 解决方案

右键新建菜单中的Office被替换为腾讯文档。原因是安装了腾讯文档软件,此软件安装时会自动将新建菜单中的Office替换为腾讯文档,下文介绍解决方案。

NSJim的博客 2928

【Scala】map,filter,flatMap函数详解

Scala中的map,filter,flatMap函数分析,是Scala的重点部分

别下完这场雪 1581

域用户无法修改密码问题的解决方案

问题描述:加域的电脑无法更改密码,提示“无法更新密码,为新密码提供的值不符合字符域的长度、复杂度或历史要求”。 问题原因:域控制器中相关设置问题,主要如下图所示(如启用复杂性、最短期限和强制密码历史) 解决方案:在域控制器中更改对应的密码策略即可: ① 禁用复杂性要求 ② 最短使用期限改为0天 ③ 强制密码历史改为0 如果出现无法更改的情况,如下图箭头所指的图标所示 代表需要在域控制器的组策...

运维日记 3万+

Scala系列8:函数式编程之map,flatten,flatmap的使用详解

0.Scala函数式编程 我们将来使用Spark/Flink的大量业务代码都会使用到函数式编程。下面这些事开发中常用的函数式编程。注意这些函数都是操作 Scala 集合的,一般会进行两类操作:转换操作(transformation )和行动操作(actions)(有些人喜欢叫他为聚合操作)。第一种操作类型将集合转换为另一个集合,第二种操作类型返回某些类型的值。 遍历( foreach ) 映射( map ) 映射扁平化( flatmap ) 过滤( filter ) 是否存在( exists )

涤生大数据 1万+

【音视频 ffmpeg 学习】 RTMP推流 mp4文件

3.当RTMP协议在互联网中传输数据的时候,消息会被拆分成更小的单元,称为消息块(Chunk)。1.RTMP(实时消息传输协议)是Adobe 公司开发的一个基于TCP的应用层协议。2.RTMP协议中基本的数据单元称为消息(Message)。下载地址:http://nginx.org/download。下载 rtmp模块 到nginx 模块下。安装nginx 和 rtmp模块。(1). linux 环境准备。下载nginx安装包。使用 vcl 播放流。

weixin_45397344的博客 2274

R语言线性混合模型(LMM)分析

它将数据表示为固定效应和随机效应的线性组合,其中固定效应表示总体均值的影响,随机效应表示个体间的随机差异。LMM的目标是通过最大似然估计或最小二乘估计来估计模型中的固定效应和随机效应的参数。LMM结合了固定效应和随机效应,能够同时考虑个体间和个体内的变异,并适用于具有相关性的数据。目前在使用LMM的R语言包中,较常用的是lme4和nlme包,它们提供了丰富的函数和工具来拟合和分析线性混合模型。面板数据分析:LMM适用于分析具有面板结构的数据,如经济学中的面板数据或教育研究中的学生评估数据。

走向CTO的路上... 2968

Scala之flatMap操作

个人理解 调用flatMap方法的是一个可迭代集合(注意:字符串是一个可迭代集合,字符串中的元素为字符) 什么类型调用的flatMap方法,则返回的也是什么类型 flatMap = map + flatten 即先对集合中的每个元素进行map,再对map后的每个元素(map后的每个元素必须还是集合)中的每个元素进行flatten 进行map的对象可以是只含一层的集合,但进行flatten操...

smart_ferry的博客 2万+

PR工具timing report中setup time的计算过程

然后去pr工具里报告report_delay_calculation/reportDelayCalculation -from related_pin -to constraint_pin。这里constraint pin就是D pin (D0 D1 D2 D3),related pin就是 CK pin。我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?

m0_61544122的博客 455

详解scala中flatmap和map的区别

FlatMap函数有一般的功能和map函数函数一样,就是经过map函数之后多了一个扁平化的过程。不过有个要求,传入的函数在处理完后返回值必须是List(或Seq),如果结果不是List(Seq),那么将出错。也就是说,传入的函数是有要求的 —— 返回值是Seq才行。这样,每个元素处理后返回一个List,我们得到一个包含List元素的List,flatMap自动将所有的内部list的元素取出来构成一...

qq_40625030的博客 1万+

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Scala中的 方法map和flatMap

map操作 map操作是针对集合的典型变换操作,它将某个函数应用到集合中的每个元素,并产生一个结果集合。 比如,给定一个字符串列表,我们可以通过map操作对列表的中每个字符串进行变换,让每个字符串都变成大写字母,这样变换后就可以得到一个新的集合。下面我们在Scala命令解释器中,演示这个过程: scala> val books = List("Hadoop", "Hive", "HDFS") books: List[String] = List(Hadoop, Hive, HDFS) .

hzp666的博客 997

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

scala中的数组,map,flatten,flatMap,foreach的基本操作

文章目录数组:mapflattenflatMapforeachworldcount 数组: val array = new Array[Int](4) //数组的声明 array(0) = 1 array(0) = 100 //数组的长度不可变,内容可变 map 将数组中的每个元素进行某种映射操作 val array = Array[Int](2,3,5,6,7) //使用 val y =...

张不帅 3406

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

scala学习笔记之Map和flatMap

应用Map和FlatMap将一个英文文档切分成单词并统计每个单词出现的次数 package com.zyc.scala import java.io.File import org.apache.commons.io.FileUtils import scala.collection.mutable /** * Created with IntelliJ IDEA. * Author: zyc2913@163.com * Date: 2020/9/20 19:50 * Version: 1.0 *

zyc2913的博客 894

Scala中的map和flatMap

Scala中的map和flatMap list中map和flatMap的实现: map 源码 abstract class List[T]{ def map[U](f: T => U): List[U] = this match { case first :: last = f(first) :: last.map(f) case Nil = Nil } 说明: map...

lds_include 464

scala map,foreach,flatMap等方法对比

应用 map方法用于对集合中的元素进行处理,返回值还是一个集合,和原集合的类型相同 scala> val x=Array(1,2,3) x: Array[Int] = Array(1, 2, 3) scala> x.map(_*2) res24: Array[Int] = Array(2, 4, 6) scala> val y=List(1,2,3) y: List[Int] = List(1, 2, 3) scala> y.map(_*2) res26: List[Int]

鸭梨的博客 699

scala的函数编程-扁平化映射 | flatMap

扁平化映射 | flatMap 扁平化映射也是将来用得非常多的操作,也是必须要掌握的。 定义 可以把flatMap,理解为先map,然后再flatten map是将列表中的元素转换为一个List flatten再将整个列表进行扁平化 方法签名 scala def flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): TraversableOnce[B] 方法解析...

汉子一枚 2417

scala flatMap个人心得

scala flatMap个人心得前几天,用scala写了一个小程序。用到了flatMap函数,发现没有想象的那么简单,所以现在写下自己的体会,方便记忆。由于本人也是初学者,如果内容有误,欢迎大家指出错误 内容: flatMap的常见用法 flatMap和Map的区别 flatMap与Future

NQMZ的博客 1万+

scala flatMap 简介

scala  flatMap的理解 一、官方例子个人解析 object FlatMapTest extends App{ //官方API用法 1.对于一阶集合flatMap返回与主对象相同的类型 2.对于map,flatMap能扁平化一层的map,把map的每个键值对都转为tuple形式

残缺的歌的专栏 5959

scala flatmap与map的区别; List、Array、ListBuffer、ArrayList、Set、元组区别

一、flatmap与map的区别 1. map会将每一条输入映射为一个新对象。{苹果,梨子}.map(去皮) = {去皮苹果,去皮梨子} 其中: “去皮”函数的类型为:A => B 不能把一行 映射为多行。 2.flatMap包含两个操作:会将每一个输入对象输入映射为一个新集合,然后把这些新集合连成一个大集合。 {苹果,梨子}.flatMap(切碎) = {苹果碎片1,苹果碎片2,梨子...

kevin 1432

Scala中的map方法和flatMap方法的区别

map方法和flatMap方法都是根据我们传入的集合,取出里面的内容变成一个新的集合返回 但是他们的用法有些区别 map方法的返回值是B,也就是自定义的,你想返回啥都可以,可以是一个String,一个数值,一个集合... flatMap方法返回值必须是GenTraversableOnce[B]类型,也就是集合类型,因为flatMap方法有一个扁平化操作,如果返回值不是集合类型,最终结果看起来会很奇怪,可以把返回值设置成一个字符串看看结果是什么样的 我写了一个map,里面的key是一个字符串,

zzds111的博客 1348

Scala Map和Flatmap的用法

代码如下: package demo.map_and_flatmapobject MapAndFlatMapDemo { def main(args: Array[String]): Unit = { /**--------map对传入的每一个元素进行映射,返回一个处理后的结果(begin)-----------------**/ //完整版 val arr1 = A...

qrjqrjqrj的专栏 591

scala 中的flatMap和map

网上很多分析flatMap和Map的不同,找几个还不错的,在加上自己的理解: 参考1 https://www.jianshu.com/p/c64f278a9902 map操作 val lineArray = Array("hello you","hello me","hello world") val lines = sc.parallelize(lineArray, 1) val words = lines.map(line =>{ line.split(" ") }) words.for

Buevara的博客 1048
上一篇: maven for scala
下一篇: Spark Master UI
DViewer
博客等级 码龄16年 16粉丝 6原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值