Map Construction Map
Immutable:
Val map = map ("sa"-> 1, "S"-> 2)
Map ("sa") = 3 // Error
Val emptymap = new scala. collection. Immutable. hashmap [String, int]
Variable:
Val MAP2 = scala. collection. mutable. Map ("sa"-> 2)
MAP2 ("sa") = 3
Val emptymap = new scala. collection. mutable. hashmap [String, int]
Note:-> used to create tuples, "sa"-> 1 ("sa", 1)
Initialization is complete with Val map = map ("sa", 1), ("S", 2 ))
Obtain the value in map:
If map does not contain the key value used in the request, an exception is thrown. Nosuchelementexception
Map ("sa") // similar to map. Get ("sa") in Java ")
To check whether a map contains a key, use the contains method.
Val SA = If (map2.contains ("sa3") MAP2 ("sa3") else 0;
Shortcut:
Val SA2 = map. getorelse ("SA2", 0)
Obtain whether the key is included at a time and obtain the value:
Val sa3 = map. Get ("sa3"); // option type,
Println (sa3.isempty)
Update values in map:
Add or update:
Map ("sa") = 3
Add or update multiple:
MAP + = ("AA"-> 4, "BB"-> 5)
Remove a key and the corresponding value:
Map-= "AA"
You can also use the + and-operations for an immutable map, but a new map is generated.
VaR map = map ("AA"-> 1)
Map = map + ("BB"-> 2)
MAP + = ("cc"-> 2)
Map-= "AA"
Iterative map:
For (K, v) <-map ){
// Todo
}
All keys:
Map. keyset
All values:
Map. Values
Reverse:
MAP2 = for (K, v) <-map) yield (v, k)
Sorted map:
Sort by key:
Sortedmap
Add order:
Linkedhashmap
Map and Java interoperability:
Convert Java properties to Scala. collection. MAP:
Import scala. collection. javaconversions. propertiesasscalamap
Val prop: scala. collection. Map [String, string] = system. getproperties ();
Convert Java map to Scala. collection. mutable. Map [String, int]:
Import scala. collection. javaconversions. mapasscalamap
Val map: scala. collection. mutable. Map [String, int] = new treemap [String, int]
Scala map to Java map:
Import scala. collection. javaconversions. mapasjavamap
Import java. AWT. Font. textattribute ._
VaR FS = map (family-> "serif", size-> 12)
VaR fonts = new font (FS)
Tuple:
Set of different types of Values
Val TP = (1, "SS", 2.0)
Access value:
TP. _ 1
TP. _ 2
TP. _ 3
Subscript starts from 1
Obtain the tuples through pattern matching:
Val (First, Second, Third) = Set
It can be used when a function returns multiple values.
Zipper operation
Val arrkey = array (1, 3, 5)
Val arrvalue = array ("A", "B", "C ")
Val tuplearr = arrkey.zip (arrvalue) // tuplearr is array (1, A), (3, B), (5, c ))
Val map = tuplearr. tomap
Scala series: map and tuple