Scala's mapping and tuple operations

Mapping and tuple operations

  • Construction of Map
    // To construct an immutable MAP map, a combination like key - > value is called dual
    val score = Map("Jack" -> 12, "Bob" -> 20)
    // You can also create a Map map in this way
    val score1 = Map(("Jack", 12), ("Bob", 20))
    // Get value according to key, similar to map.get(key) in java. If you get a nonexistent key, an error will be reported instead of null
    println(score("Jack"))
    // Get element does not exist give no element reminder
    val flag = if (score.contains("haha")) score.get("haha") else "no such element"
    val flag1 = score.getOrElse("haha", "no such element")
    // Create a variable Map
    val score = scala.collection.mutable.Map("Jack" -> 12, "Bob" -> 20)
  • Update values in map
In a variable mapping, you can update the value of a mapping by using () to the left of the = sign:
//Update variable Map values
scores("Bob") = 10
 //Add new key value
scores("haha")=7
 //You can also use the + = action and create a mapping relationship
scores +=("Michael" -> 22)
//Remove the value corresponding to a key
score -=("Michael")
  • Iterative mapping
for((k,v) <- mapping) This can get each key value pair
// Like java, keySet and values methods can be used, and the values method will return an iterable
score.keySet // Return to similar ("Bob","Michael")
// Get the value of map
for (v <- score.values) println(v)
  • Sort mapping

    During operation mapping, you need to select an implementation - hash table or balance tree. By default, Scala Chinese hash table is used. If you want to access all keys in sequence, you need a tree map

val scores = scala.collection.immutable.SortedMap("Bob" -> 10,"michael" -> 12)
  • Interoperability with java
// Import Scala.collection.javaconversions.mapascalamap and then specify the Scala mapping type to trigger the conversion
val scores:scala.collection.mutable.Map[String,Int] = new java.util.TreeMap[String,Int]
// import scala.collection.javaConversions.propertiesAsScalaMap
val props :scala.collection.Map[String,String] = System.getProperties()
// All of the above is to turn java map into Scala map, and you can turn Scala map into java map
import scala.collection.javaConversions.mapAsJavaMap
  • tuple

The set of mapped key value pairs, the simplest form of dual tuples - while the different types of tuples are worth aggregation

(1,95.27,"Bob") Is a tuple of type(Int,Double,java.lang.String)Can method_1,_2,_3 Access tuples such as:
    val l = (1,2.34,"Ha-ha")
    println(l._2)
  • Zipper operation
// Use tuples to map them using the zip method
    val symbols = Array("<","-",">")
    val counts = Array(2,10,2)
    val pairs = symbols.zip(counts)
    println(pairs.toBuffer)
    // Printing
    for ((s,n) <- pairs) Console.print(s * n)

Keywords: Scala Java

Added by robert_gsfame on Sat, 04 Jan 2020 20:02:21 +0200