Scala notes finishing (ii): Scala data Structures-arrays, maps, and tuples

Source: Internet
Author: User
Tags function definition

[TOC]

Array fixed-length arrays

If you need an array of the same length, you can use the arrays in Scala. For example:

val numsArray = new Array[Int] (30) //长度为30的整数数组,所有元素初始化为0val stringArrays = new Array [String] (30) //长度为30的字符串数组,所有元素初始化为nullval sHello = Array("Hello", "World") //长度为2的Array[String]类型是推断出来的,已提供初始值就不需要newsHello(0) = "Hello Tom",使用()而不是[]来访问元素

In the JVM, Scala's array is implemented as a Java array. The array in the example is of type java.lang.string[] in the JVM. An Int, double, or other array corresponding to the base type in Java is an array of primitive types.

For example, Array(2,3,5,6,7,10, 11) in the JVM is a int[].

Fixed-length Array array-assignment
    • Method 1
val stringArrays = new Array[String] (5) stringArrays(0) = “tom”
    • Method 2
val array = Array(1, 2, 3, 4, 5)
    • Method 3
// Array.fill(length)(value)val array = Array.fill(5)(3.5)

If the fill second parameter writes only one value, then all elements of the array are that value, but if the second argument is one iterator or random the array is assigned the value.

val array = Array.fill(2)(math.random)
Variable-length array arraybuffer

1, for that length as needed to change the array, Java has arraylist,c++ vector. The equivalent data structure in Scala is Arraybuffer

2, Arraybuffer is a kind of mutable data container, relative to the array, the biggest difference is that you can freely delete elements. When the Arraybuffer is built, it can also be converted to the immutable array container.

import scala.collection.mutable.ArrayBufferval buffer = ArrayBuffer[lnt]() // 或者new ArrayBuffer [int],一个空的数组缓冲,准备存放整数buffer += 1 // ArrayBuffer (1),用+=在尾端添加元素buffer.append(300)buffer += (1,2,3,5) // ArrayBuffer(1,1,2,3,5),在尾端添加多个元素,以括号包起来buffer ++= Array(8, 13, 21) // ArrayBuffer(1, 1, 2, 3, 5, 8,13, 21) //用++=操作符追加任何集合buffer.insert(2, 150) //在第2元素(索引)后插入150:buffer.insert(3, 147,21) //在第2元素后插入147,21:buffer.trimEnd(5) // ArrayBuffer(1, 1, 2),移除最后5个元素,在数组缓冲的尾端添加或移除元素是一个高效的操作buffer.remove(index, n) //移除第index元素后的n个元素

A complete example is as follows:

import scala.collection.mutable.ArrayBufferobject _07ArrayBufferDemo {    def main(args:Array[String]):Unit = {        val ab = new ArrayBuffer[Int]()        // 增        ab += 1        println(ab)        ab.append(2)        println(ab)        ab += (3, 4, 5)        println(ab)        ab ++= Array(6, 7)        println(ab)        // insert        ab.insert(3, -1, -2)    // 可以在某一个位置插入多个元素        println(ab)        // 删        ab.trimEnd(1)   // 删除数组末尾的1个元素        println(ab)        ab.remove(3, 1) // 从索引位置3开始删除,删除2个元素        println(ab)        // 改        ab(3) = -3        println(ab)        // 查        println("==============================")        for(i <- ab) {            println(i)        }    }}
Iterating through an array
val array = Array(1, 2, 3, 4, 5)

1, full traversal common traversal (//If you do not need to use subscript, in this way the simplest)

for(i <- array) print(i +" ")

2. Conditional traversal

for(i <- arrayif i !=2 ) print(i +“ ”) //打印出除2之外的所有整数的值

3. For deduction type

In front, you see how to manipulate arrays like Java or C + +. But in Scala, you can go farther. Starting with an array or array buffer, it is easy to convert it in some way. These conversion actions do not modify the original array, but instead produce a completely new array. Use the For deduction like this:

val arr = ArrayBuffer(1, 3, 2, -1, -2)for(i <- 0 until arr.length) yield arr(i) * 2 //将得到Vector(2, 6, 4, -2, -4)for(i <- array) yield print(i * 2)  // ArrayBuffer[Unit] = ArrayBuffer((), (), (), (), ())

Another method of equivalence (thanks to the idea of functional programming), some programmers with functional programming experience tend to use filter and map instead of guard and yield, which is just the same style as what the For loop does. You can choose any of the following preferences:

array.filter( _ > 0).map{ 2 * _}.foreach(println(_)) //生成array中的正数的两倍的新集合array.filter {_ > 0}.map {2 * _}.foreach(println //另一种写法
Common algorithms (Scala built-in functions)

1. Summation and sequencing

println(Array(1,7,2,9).sum)

2, to find the maximum value

3. Sorting

    • Ascending
val b = ArrayBuffer(1,7,2, 9)val bSorted = b.sorted //1,2,7,9b.sortWith(_ < ).foreach(println())

Descending

b.sortWith(_ > ).foreach(println())

4. Display array Contents

println(b.mkString("And")) //分隔符println(b.mkString("<",",",">"))//<1,7,2,9> //指定前缀、分隔符、后缀
Multidimensional arrays

1. Fixed-length multidimensional arrays (as in Java, multidimensional arrays are implemented by arrays)

val array = new Array[Array[Int]](5) scala> val array = new Array[Array[Int]](5)array: Array[Array[Int]] = Array(null, null, null, null, null)

2. The multidimensional array in Scala is the same as in Java, and multidimensional arrays are arrays of arrays. (Recommended in this way)

By Array.ofDi[类型](维度1, 维度2, 维度3,….) declaring a multidimensional array, such as declaring a two-dimensional array;

Or you can define this with ofDim[T](rows,column, height,…) a function definition, but you can define up to five-dimensional arrays.

scala> val array = Array.ofDim[Double](2,3)array: Array[Array[Double]] = Array(Array(0.0, 0.0, 0.0), Array(0.0, 0.0, 0.0))scala> for(a <- array) println(a.toList)List(0.0, 0.0, 0.0)List(0.0, 0.0, 0.0)

3. Variable length multidimensional array

val arr1 = new ArrayBuffer[ArrayBuffer[Int]]()
Conversion of fixed-length arrays and variable-length arrays

1. Fixed-length array a converts to variable-length array:

array = a.toBuffer

2. The variable-length array is converted into a fixed-length array a:

a = array.toArray
Interoperability with Java (understanding)

Since the Scala array is implemented in a Java array, you can pass it back and forth between Java and Scala. You can introduce implicit conversion methods in scala.collection.JavaConversions so that when you call a Java method, these objects are automatically wrapped into a Java list.

For example, the Java.lang.ProcessBuilder class has a constructor that takes list<string> as its parameter. Here's how to invoke it in Scala:

    • Scala to Java conversion work
def conversionArray: Unit ={    import scala.collection.JavaConversions.bufferAsJavaList    import scala.collection.mutable.ArrayBuffer    val command = ArrayBuffer("ls", "-al", "/home/cay")    val pb = new ProcessBuilder(command) // Scala到Java的转换    println(pb.command())
    • Conversion between Java and Scala
def conversionArray: Unit ={    import scala.collection.JavaConversions.bufferAsJavaList    import scala.collection.mutable._    val command = ArrayBuffer("ls", "-al", "/home/cay")    val pb = new ProcessBuilder(command) // Scala到Java的转换    println(pb.command())    import scala.collection.JavaConversions.asScalaBuffer    import scala.collection.mutable.Buffer    val cmd: Buffer[String] = pb.command() // Java到Scala的转换    println(cmd.head +"\t tail=> " + cmd.tail)  }
MAPMAP Create

1. Non-variable mappings

We can construct a mapping like this:

val personAges = Map("Alice"-> 20, "Job"->28, "Garry"->18)

The code above constructs an immutable map[string,int] whose value cannot be changed.

You can also use this method to create a map

val personAges = Map(("Alice"-> 20), ("Job"->28),("Garry"->18))

Note:-> is used to create tuples, "sa" and 1 ("sa", 1)

2. Variable mapping

If you want a mutable mapping, use the

val personAges = scala.collection.mutable.Map("Alice"->20, "Job"->28, "Garry"->18)

If you want to start with an empty map, you need to select a mapping implementation and give the type parameter:

val personAges1 =new scala.collection.mutable.HashMap [String, Int]

In Scala, a map is a set of dual. Duality is simply a group of two values that are not necessarily of the same type, such as ("Alice", 10)

Get the values in the map
    • Mode 1
println("Alice=>  " + personAges.get("Alice111"))

Similar to Personages.get ("Alice111") in Java, an exception is thrown if the map does not contain the key used in the request. To check if there is a specified key in the map, you can use the Contains method.

    • Mode 2:contains method
val personAlice = if (personAges.contains ("Alice")) { personAges("Alice") }else 0println("personAlice===> " + personAlice)
    • Mode 3
println("Alice1.else=>  " + personAges.getOrElse("Alice",0))     // 如果映射包含键“Alice",返回对应的值;否则,返回0

Finally, the map. Get (key) Such a call returns an option object, either some (the key corresponding to the value), or the None,option object has a get function, directly called to get the original map of the value corresponding to the key

Update the values in the map

1. Update variable Mappings

In a mutable map, you can either update the value of a map or add a new mapping relationship by using the () to the left of the = sign:

personAges("Job") = 31 // 更新键"Job"对应的值personAges("Garry") = 27 // 增加新的键/值对偶到personAges

Alternatively, you can add multiple relationships with the + = operation:

personAges += ("Bob"-> 10, "Fred"->7)

To remove a key and its corresponding value, use the-= operator:

personAges -="Alice"

2. Update non-volatile mappings

Although you cannot update an immutable mapping, you can do something equally useful to get a new mapping that contains the required updates

val personAges = Map("Alice" -> 20, "Job" -> 28, "Garry" -> 18)val newPersonAges = personAges + ("Job" -> 10,"Fred" -> 7) // 更新过的新映射println("newPersonAges=> " + newPersonAges)

You can also declare var variables

var personA = Map("Alice"-> 20, "Job"->28, "Garry"->18)personA = personA + ("Bob"->10, "Fred"->7)println("personA=> " +personA)

Remove the values of the immutable mappings at the same time

personA = personA -"Alice"  // 其实也相当于是重新创建了一个新的Map对象println("remove.personA => "+ personA)
Traverse Map
val personAges = Map ("Alice"-> 20, "Job"->28, "Garry"->18)for ((k,v) <- personAges) print("k=> " + k +"\t v=> " + v +" ") println()   // 同时获取key和valuefor((k,_)<- personAges) print("k => " + k +" ") println()   // 只获取keyfor(k <- personAges.keySet) print("kkkk=> " + k +" ") println() // 只获取keyfor((_,v) <- personAges) print("v=> " + v +" ") println()   // 只获取valuefor ( v <- personAges.values) print("vvvv=> " + v)  // 只获取valuescala> person.foreach(me => println(me._1)) // 只获取key,通过元组的方式jielingxiaoqiutianxpleafscala> person.foreach(me => println(me._2)) // 只获取value,通过元组的方式221723

To invert a map, that is, the position of the swap key and the value, you can use:

for ( (k,v) <- personAges) yield print(v,k)scala> for((k,v) <- person) yield print(v, k)(22,jieling)(17,xiaoqiutian)(23,xpleaf)res177: scala.collection.mutable.Iterable[Unit] = ArrayBuffer((), (), ())scala> for((k,v) <- person) yield(v, k) // 应该是这样才对,因为上面的方式值为空的res178: scala.collection.mutable.Map[Int,String] = Map(23 -> xpleaf, 17 -> xiaoqiutian, 22 -> jieling)
Map sort
val personAges = scala.collection.immutable.SortedMap("Alice"->10,"Fred"->7,"Bob"->3,"Cindy"->8)    // 会按照key的字典顺序进行排序println("personAges==> " + personAges)  // personAges==> Map(Alice -> 10, Bob -> 3, Cindy -> 8, Fred -> 7)val months = scala.collection.mutable.LinkedHashMap("January" -> 1,"February" -> 2,"March" -> 3)    // 创建一个顺序的Mapmonths += ("Fourth" -> 4)println("months=> " + months)   // months=> Map(January -> 1, February -> 2, March -> 3, Fourth -> 4)
Tuple tuple definitions

A map is a collection of key/value duality. Duality is the simplest form of tuple (tuple), which is the aggregation of different types of values. The value of a tuple is formed by enclosing a single value in parentheses. For example:

(1, 3.14, "Fred")

is a tuple that is of type:

Tuple3 [Int, Double, java.lang.String]

Here is a simple way to define tuples:

val t = (1,3.14, "John")println(t._1 +"\t " + t._2 +"\t " + t._3)

It is important to note that the tuple's tuples start at 1 instead of 0, and the positions in the array or string are different. You can write t._2 as T-_2, with spaces instead of periods, but not t_2

Of course, it can be defined in the following way:

scala> val tuple = new Tuple4[String, Int, String, Double]("xpleaf", 1, "guangdong", 17000)tuple: (String, Int, String, Double) = (xpleaf,1,guangdong,17000.0)
Get tuples
val t = (1, 3.14, "John", "Garry")println(t._1 +"\t " + t._2 +"\t " + t._3 + "\t" + t._4)val (first,second,third,fourth) = t // 这种赋值方式与Python是一样的,通过元组赋值给多个值println(first + "\t" + second + "\t" + third + "\t" + fourth)println("New York".partition ( _.isUpper))  // (NY,ew ork)

Traversing elements:

t.productIterator.foreach(x => print(x +" "))

Scala note Finishing (ii): Scala data Structures-arrays, maps, and tuples

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.