Scala - Map operation

1. Definitions Map

1.1, the definition of immutable Map that is immutable

scala> val m = Map("Tom" -> 55,"Jak" -> 56,"Jim" -> 66)
m: scala.collection.immutable.Map[String,Int] = Map(Tom -> 55, Jak -> 56, Jim -> 66)

By // -> symbol definitions

-------------------------------------------------------------------------------

scala> val m = Map(("Tom",23),("Jack",45),("Tinna",66))
m: scala.collection.immutable.Map[String,Int] = Map(Tom -> 23, Jack -> 45, Tinna -> 66)

// define by way of tuples

------------------------------------------------------------------------------

1.2, the variable definition Mapmutable

scala> val m = scala.collection.mutable.Map("Tom" -> 55,"Jak" -> 56,"Jim" -> 66)
m: scala.collection.mutable.Map[String,Int] = Map(Jim -> 66, Tom -> 55, Jak -> 56)

// define a variable by specifying scala.collection.mutable.Map Map

============================================================

2. Access Map elements

scala> m
res0: scala.collection.mutable.Map[String,Int] = Map(Jim -> 66, Tom -> 55, Jak -> 56)

scala> m("Tom")
res1: Int = 55

scala> m("Toms")
java.util.NoSuchElementException: key not found: Toms
at scala.collection.MapLike$class.default(MapLike.scala:228)
at scala.collection.AbstractMap.default(Map.scala:59)
at scala.collection.mutable.HashMap.apply(HashMap.scala:65)
... 32 elided

// direct access to value elements of the Map, but once this element is not present does not complain, will complain

scala> m.get("Tom")
res2: Option[Int] = Some(55)

scala> m.get("Toms")
res6: Option[Int] = None

// Get the value of the element by the get method, once this element is not present, then it will return None

scala> m.getOrElse("Tom",-1)
res4: Int = 55

scala> m.getOrElse("Toms",-1)
res7: Int = -1

// getOrElse method, if present, the element will return value, if the element does not exist, then it will return -1

================================================================

3, change the value of Map elements must be mutable can modify the Map

scala> m
res8: scala.collection.mutable.Map[String,Int] = Map(Jim -> 66, Tom -> 55, Jak -> 56)

scala> m("Tom") = 65

scala> m
res10: scala.collection.mutable.Map[String,Int] = Map(Jim -> 66, Tom -> 65, Jak -> 56)

// modify the value of the element by directly modifying the way

=================================================================

4, each element traversing Map

scala> for(s <- m)println(s)
(Jim,66)
(Tom,65)
(Jak,56)

Value // Access Map for loop through each element

-----------------------------------------------------

scala> m.foreach (println)
(Jim, 66)
(Tom 65)
(As, 56)

// value accessed via foreach Map Map of the various elements

=========================================

5, mutable is variable, Val is immutable, whether the two are in conflict?

The two are not in conflict

Guess you like

Origin www.cnblogs.com/jeff190812/p/11823219.html