scala基础 -- map

Posted pocahontas

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了scala基础 -- map相关的知识,希望对你有一定的参考价值。

 

creates Map

val weights = Map("cat" -> 10, "elephant" -> 200000)
val weight = weights("elephant")
println(weight)

 

val colors = Map(("bird", "blue"), ("fox", "red"))
val result1 = colors("bird")
println(result1)

 adds key, value to map

val zoo = Map("frog" -> 1, "lion" -> 1)
val all = zoo + ("zebra" -> 1)

 

iterate over all values.

zoo.keys.foreach(println(_))
for (value <- zoo.values) 
    println(value)

 

getOrElse

// Use a default value if the key does not exist.
val result3 = sizes.getOrElse("Small", 0)
if (result3 == 0) 
    println("Zero, else value")

 

val result2 = sizes.get("Large")
if (result2.isDefined) 
    println(result2)
    val number = result2.get
    println(number)

 equals

val map1 = Map((10, true), (20, false))
val map2 = Map((20, false), (10, true))
val map3 = Map((20, true), (10, true))

// These two maps are structurally equal.
if (map1.equals(map2)) 
    println("Maps equal")

 Output

Maps equal

 

以上是关于scala基础 -- map的主要内容,如果未能解决你的问题,请参考以下文章

2021年大数据常用语言Scala(十八):基础语法学习 Map对象

scala言语基础学习三

Scala:基础知识02

Scala基础语法学习

Scala基础语法学习

Scala基础篇