Scala: tuples, arrays, maps

Tuple: tuple, aggregation of values of different types.
Combine a fixed number of items so that they can be passed as a whole. Unlike arrays or lists, tuples can hold different types of objects, but they are also immutable.
The actual type of the ancestor depends on its component type. For example, the following type is Tuple3[Int,String,String]
Index starts at 1
object Tuple {
  def main(args: Array[String]): Unit = {
    val triple1 = (100, "Scala", "Spark")
    println(triple1._1)
    println(triple1._2)
    println(triple1._3)
    //They can also be used to pass data value lists as messages between participants in concurrent programming.
    val triple2 = (4, 3, 2, 1)
    val sum = triple2._1 + triple2._2 + triple2._3 + triple2._4

    println("Sum of elements: " + sum)

    //Iteration of tuples
    val triple3 = (4, 3, 2, 1)

    triple3.productIterator.foreach { i => println("Value = " + i) }

    //Tuple to string: available Tuple.toString()Method to concatenate all elements of a tuple into a string
    val triple4 = new Tuple3(1, "hello", Console) //Explicit use here

    println("Concatenated String: " + triple4.toString())
    //Exchange elements: can use Tuple.swap Method exchange Tuple2 Elements in
    val triple5 = new Tuple2("Scala", "hello")

    println("Swapped Tuple: " + triple5.swap)

  }
}
Arrays: Array
1. Fixed length array
val nums = new Array[Int](10) length is 10 initial element is 0
2. Variable length array
ArrayBuffer
3. Common algorithms
sum,max,sorted
4. Multidimensional array
Multidimensional arrays are implemented by arrays of arrays
5. Array conversion
Array conversion in Scala will not change the original array, only a new array will be generated
object ArrayOps {
  def main(args: Array[String]): Unit = {


    //ArrayBuffer
    val arraybuffer = ArrayBuffer[Int]()
    //Additive elements
    arraybuffer += 1
    //use+=Add elements at the end
    arraybuffer += (2,3,4,5)
    //Add multiple elements,Can use++=Add any collection
    arraybuffer ++= Array(6,7,8)
    //Removing Elements,It can be from the head or the tail
    arraybuffer.trimStart(1)
    arraybuffer.trimEnd(3)
    //You can also insert or overflow elements from any location, which is not efficient
    arraybuffer.insert(2,11)//The first parameter is the index and the second is the insert value
    arraybuffer.remove(3,2)//The first parameter is index, and the second parameter is the number of removed
    //Sometimes you need to build a Array,But we don't know how many elements we need, we can build an array buffer
    arraybuffer.toArray

    //Traversal of array
    val array = Array(1, 2, 3, 4, 5)
    //until yes RichInt Class to return all data less than the upper limit
    for (i <- 0 until array.length) {
      println(array(i))
    }
    //If we don't need subscripts in the loop body, we can directly access array elements
    for(elem <- array){
      println(elem)
    }

    arraybuffer.sum
    arraybuffer.max
    arraybuffer.sorted
    //Multidimensional array
    //this Double The multidimensional array type of is Array[Array[Double]],Construct this array using ofDim Method
    val matrix1 = Array.ofDim[Double](3,4)//3 Row, 4 column
    //Access element
    //matrix1(row)(column)
    //Irregular array, each row has different length
    val  matrix2=new Array[Array[Int]](10)
    for(i <- 0 until matrix2.length){
      matrix2(i) = new Array[Int](i+1)
    }

    //Array conversion
    //yield
    val a = Array(2,3,5,6)
    val result = for(elem <- a) yield  2 * elem
    //If you are not satisfied, you can pass the guard
    val result1 = for(elem <- a if elem % 2==0) yield  2 * elem
  }
}
Programmer's famous saying: "if there is only one data structure, use hash table."
Map(k,v)
1. Construct map mutable.map [string, int]; immutable.map [string, int]
2. Get and update mapping values
3. Iterative mapping for ((k,v) - > mapping) processing k,v
4. Sorted map
object MapOps {
  def main(args: Array[String]): Unit = {
    var scores1=Map("john" -> 10,"Alice" -> 20,"Bob" -> 30)
    //The above code constructs an immutable mapping Map[String,Int],Its value cannot be changed,because Map The default is to call immutable The source code of the package is: val Map = immutable.Map
    //Variable mapping
    val scores2=scala.collection.mutable.Map("john" -> 10,"Alice" -> 20,"Bob" -> 30)
    //Empty mapping, type selection required
    val scores3=new scala.collection.mutable.HashMap[String ,Int]

    //Get the value in the map: you can get the value according to the key
    val johnScore=scores1("john")//Similar Java Medium scores.get("john")
    //Check if a value is included in the map
    val bobScore = if(scores1.contains("Bob")) scores1("Bob") else 0
    //Shortcut writing
    val aliceScore = scores1.getOrElse("Alice",0)
    //Update the value in the map, which needs to be in the variable map
    scores2("john")=80
    scores2 += ("Boole" -> 50,"LiLei" -> 45)
    //Although immutable mapping is immutable by definition, you can
    val newScores=scores1 + ("HanMei" -> 99)
    //Similarly, you need to remove a value from the immutable map to use-Unmap the key
    scores1 = scores1 - "Alice"

    //Iterative mapping: you can Scala Of for Using pattern matching in a loop
    //If you only need access to keys and values, you can use the keySet and values,values Method returns a Iterable,You can use this in a loop Iterable
    scores1.keySet //A similar Set Of("john","Alice","Bob" )Such sets
    for(i <- scores1.values) println(i)

    //Sorted map:By default, Scala Given a hash table, we need to access all keys in order. We need a tree map

    val scores4 = scala.collection.immutable.SortedMap("john" -> 10,"Alice" -> 20,"Bob" -> 30)

    //If you want to insert all keys in order
    val scores5 = scala.collection.mutable.LinkedHashMap("john" -> 10,"Alice" -> 20,"Bob" -> 30)




  }
}

Tags: Scala Spark Programming less

Posted on Mon, 02 Dec 2019 15:31:44 -0500 by kristofferlc