scala中map添加值_如何在Scala Map中反转键和值
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添加值
總結
以上是生活随笔為你收集整理的scala中map添加值_如何在Scala Map中反转键和值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: scala 空列表_如何在Scala中展
- 下一篇: hwd是长宽高吗_五菱皮卡要来了,五种形