Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Scala Note processing (2): Scala data structure-Array, map and tuple

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

[TOC]

Array fixed length array

If you need an array of constant length, you can use Array in Scala. For example:

Val numsArray = new Array [Int] (30) / / Integer array of length 30, all elements are initialized to 0val stringArrays = new Array [String] (30) / / string array of length 30, and all elements are initialized to nullval sHello = Array ("Hello", "World") / / Array [string] type of length 2 is inferred NewsHello (0) = "Hello Tom" is not required if the initial value is provided, using () instead of [] to access the element

In JVM, the Array of Scala is implemented as an array of Java. The array in the example is of type java.lang.String [] in JVM. Int, Double, or other arrays that correspond to primitive types in Java are arrays of primitive types.

For example, Array (2, 3, 5, 6, 7, 10, 11) is an int in JVM.

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

If the second parameter of fill writes only one value, then all elements of the array will be that value, but if the second parameter is an iterator or random, then the array will be assigned to their value.

Val array = Array.fill (2) (math.random) variable length array ArrayBuffer

1. For arrays whose length varies as needed, Java has ArrayList,C++ and vector. The equivalent data structure in Scala is ArrayBuffer

2. ArrayBuffer is a data container for mutable. Compared with Array, the biggest difference is that you can add and delete elements freely. When the ArrayBuffer is built, it can also be converted into an Array container for immutable.

Import scala.collection.mutable.ArrayBufferval buffer = ArrayBuffer [lnt] () / / or new ArrayBuffer [int], an empty array buffer, ready to store the integer buffer + = 1 / / ArrayBuffer (1), add elements buffer.append (300) buffer + = (1line 2) / ArrayBuffer (1) at the end, add multiple elements at the end Enclose buffer + + = Array (8jue 13,21) / / ArrayBuffer (1,1,2,3,5,8 ArrayBuffer 13,21) / / append any set buffer.insert (2150) with the + + = operator / / insert 150:buffer.insert (3,1472121) after the second element (index) / / insert 14721J buffer.trimEnd (5) / ArrayBuffer (1,1,2) after the second element, remove the last five elements Adding or removing elements at the end of the array buffer is an efficient operation to buffer.remove (index, n) / remove n elements after the index element

A complete example is as follows:

Import scala.collection.mutable.ArrayBufferobject _ 07ArrayBufferDemo {def main (args: array [string]): Unit = {val ab = new ArrayBuffer [Int] () / add 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) / / you can insert multiple elements println (ab) / / delete ab.trimEnd (1) / / delete one element at the end of the array println (ab) ab.remove (3,1) / / delete from index position 3 Delete 2 elements println (ab) / / change ab (3) =-3 println (ab) / / check println ("=") for (i val array = new Array [Array]] (5) array: array [Array] = Array (null, null)

2. The multidimensional array in Scala is the same as in Java, and the multidimensional array is an array of arrays. (this method is recommended)

Through Array.ofDi [Type] (Dimension 1, Dimension 2, Dimension 3, … (.) To declare a multidimensional array, such as a two-dimensional array

Or it can be defined in this way as ofDimt [T] (rows,column, height, …) Function definition, but up to a five-dimensional array can be defined.

Scala > val array = Array.ofDim [Double] (2Power3) array: Array [Array [double]] = Array (Array (0.0,0.0,0.0), Array (0.0,0.0,0.0) scala > for (a 20, "Job"-> 28, "Garry"-> 18)

The above code 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:-> used to create tuples, "sa"-> 1 means ("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 mapping, you need to select a mapping implementation and give the type parameters:

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

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

Get the value mode 1println in Map ("Alice= >" + personAges.get ("Alice111"))

Similar to personAges.get ("Alice111") in Java, an exception is thrown if the mapping does not contain the key used in the request. To check whether 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 3println ("Alice1.else= >" + personAges.getOrElse ("Alice", 0)) / / if the mapping contains the key "Alice", return the corresponding value; otherwise, return 0

Finally, a call such as mapping. get (key) returns an Option object, either Some (the value corresponding to the key) or None,Option object has a get function, which can be called directly to get the value corresponding to the key in the original Map.

Update values in Map

1. Update variable mapping

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

PersonAges ("Job") = 31 / / update key "Job" corresponding to the value personAges ("Garry") = 27 / / add a new key / value pair to personAges

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

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

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

PersonAges-= "Alice"

2. Update the invariant mapping

Although you can't 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) / / updated new mapping 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 value of the immutable map at the same time

PersonA = personA-"Alice" / / is actually equivalent to recreating a new Map object println ("remove.personA = >" + personA) traversing Mapval personAges = Map ("Alice"-> 20, "Job"-> 28, "Garry"-> 18) for ((kjorv) person.foreach (me = > println (me._1)) / / only get key, jielingxiaoqiutianxpleafscala > person.foreach (me = > println (me._2) / / only get value by tuple By tuple 221723

To reverse a mapping, that is, the position of exchanging keys and values, you can use:

For ((KCindy v) xpleaf, 17-> xiaoqiutian, 22-> jieling) Map sort val personAges= scala.collection.immutable.SortedMap ("Alice"-> 10, "Fred"-> 7, "Bob"-> 3, "Cindy"-> 8) / / will sort println ("personAges== >" + personAges) / / personAges== > Map (Alice-> 10, Bob-> 3, Cindy-> 8) according to the dictionary order of key. Fred-> 7) val months= scala.collection.mutable.LinkedHashMap ("January"-> 1, "February"-> 2, "March"-> 3) / / create a sequence of Mapmonths + = ("Fourth"-> 4) println ("months= >" + months) / / months= > Map (January-> 1, February-> 2, March-> 3, Fourth-> 4) tuple tuple definition

A mapping is a collection of key / value pairs. Duality is the simplest form of tuple, which is the aggregation of different types of values. The values of tuples are formed by enclosing individual values in parentheses. For example:

(1,3.14, "Fred")

Is a tuple of type:

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

Here is a simple way to define tuples:

Val t = (1mai 3.14, "John") println (t. Girls 1 + "\ t" + t. Girls 2 + "\ t" + t. 3)

It is important to note that, unlike positions in an array or string, tuples start with 1 instead of 0. You can write t.room2 as tactile 2, that is, with spaces instead of periods, but not as twee2.

Of course, it can also be defined in the following ways:

Scala > val tuple = new Tuple4 [String, Int, String, Double] ("xpleaf", 1, "guangdong", 17000) tuple: (String, Int, String, Double) = (xpleaf,1,guangdong,17000.0) get tuple val t = (1,3.14, "John", "Garry") println (t. Fourth) = t / / this assignment is the same as Python Assign multiple values println (first + "\ t" + second + "\ t" + third + "\ t" + fourth) println ("New York" .partition (_ .isUpper)) / / (NY,ew ork) through tuples

Traversing elements:

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report