scala中map添加值_如何在Scala Map中反转键和值

本文介绍了如何在Scala中反转Map的键和值。通过一个示例程序展示了反转过程,并强调了在反转前确保键和值唯一以避免错误的重要性。当值不唯一时,反转操作会删除重复的键值对。
摘要由CSDN通过智能技术生成

scala中map添加值

A Map is a data structure that stores data as key: value pair.

映射是一种将数据存储为键:值对的数据结构。

Syntax:

句法:

    Map(key->value, key->value)

反转地图中的键和值 (Reversing Keys and values in Map)

Here, we will see a program to reverse keys and values in Scala Map. We will reverse the values to keys and the keys to pairs.

在这里,我们将看到一个在Scala Map中反转键和值程序 。 我们将值反转为键,将键反转为对。

So, before this, we will have to make sure that both keys and values of the initial map are unique to avoid errors.

因此,在此之前,我们必须确保初始映射的键和值都唯一以避免错误。

Program:

程序:

object myObject { 
	def main(args:Array[String]) { 
		val bikes = Map(1->"S1000RR" , 2->"R1", 3->"F4" ) 
        println("Inital map: " + bikes)		
		val reverse = for ((a, b) <- bikes) yield (b, a) 
		println("Reversed map: " + reverse) 
	} 
} 

Output

输出量

Inital map: Map(1 -> S1000RR, 2 -> R1, 3 -> F4)
Reversed map: Map(S1000RR -> 1, R1 -> 2, F4 -> 3)

Explanation:

说明:

Here, we have declared a map and then reversed its values. In the reverse variable, we have inserted value that is reverse of each pair of the original map, the yield methods take the (key, value) pair and returns (value, key) pair to the reverse map.

在这里,我们声明了一个映射,然后反转了它的值。 在反向变量中,我们插入了与原始映射的每对相反的值,yield方法采用( key,value )对,然后将( value,key )对返回到反向映射。

What if values are not unique?

如果值不是唯一的怎么办?

There is a thing that is needed to be considered is both key-value pairs should be unique. But if we insert a duplicate in value, in the reverse map this will delete that pair.

有一点需要考虑的是,两个键值对都应该是唯一的。 但是,如果我们在值中插入重复项,则在反向映射中将删除该对。

Program:

程序:

object myObject { 
	def main(args:Array[String]) { 
		val bikes = Map(1->"S1000RR" , 2->"R1", 3->"F4", 4->"S1000RR" ) 
        println("Inital map: " + bikes)		
		val reverse = for ((a, b) <- bikes) yield (b, a) 
		println("Reversed map: " + reverse) 
	} 
} 

Output

输出量

Inital map: Map(1 -> S1000RR, 2 -> R1, 3 -> F4, 4 -> S1000RR)
Reversed map: Map(S1000RR -> 4, R1 -> 2, F4 -> 3)

So, the code runs properly but the reverse will delete the pair 4->S100RR to make all the keys of reverse map unique.

因此,代码可以正常运行,但是反向键将删除对4-> S100RR以使反向键的所有键都唯一。

翻译自: https://www.includehelp.com/scala/reverse-keys-and-values-in-scala-map.aspx

scala中map添加值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值