scala代碼示例
Scala tuple is a collection of items together of different data types. Scala tuple is immutable.
Scala元組是不同數據類型的項目的集合。 Scala元組是不可變的。
For example;
scala入門、 例如;
val s1 = (12,"Harry")
Here we are declaring a tuple s1 that holds student id of integer type and student name of String data type.
在這里,我們聲明一個元組 s1,其中包含整數類型的學生ID和字符串數據類型的學生名稱。
The above tuple s1 can also be declared as;
上面的元組s1也可以聲明為:
val s1 = new Tuple2(12,"Harry")
scala. 動態二維數組?The type of the tuple depends upon the number of elements contained and the data types of those elements. The type (12,”Harry”) is of type Tuple2[Int,String].
元組的類型取決于所包含元素的數量以及這些元素的數據類型。 類型(12,“ Harry”)的類型為Tuple2 [Int,String] 。
The upper limit for the number of elements that a tuple can contain is 22. For each tuple of TupleN type, where 1 <= N <= 22Let us consider an example of how to access the elements of the tuple;Consider a tuple of Integer data type as
元組可以包含的元素數的上限是22。對于TupleN類型的每個元組,其中1 <= N <= 22讓我們考慮一個如何訪問元組的元素的示例;請考慮一個Integer元組數據類型為
val m1 = (20,12,16,4)
Elements of the tuple t1 can be accessed as m1._1
for first element, m1._2
for second element and so on.
scala元組。 元組t1的元素可以作為第一個元素的m1._2
訪問, m1._2
對于第二個元素則作為m1._1
訪問,依此類推。
val mul = m1._1* m1._2*m1._4
We are accessing the first, second and fourth element of tuple m1 and multiplying the elements storing the result in variable mul.
我們正在訪問元組m1的第一,第二和第四元素,并將結果存儲在變量mul中的元素相乘。
In all our earlier examples, we have used Scala shell to execute programs or compile/run scala code from command line. But today we will use the Scala eclipse IDE for executing the program. You can download the Eclipse IDE for Scala from https://scala-ide.org/download/sdk.html according to your operating system.
在所有先前的示例中,我們都使用Scala shell執行程序或從命令行編譯/運行scala代碼。 但是今天我們將使用Scala eclipse IDE來執行程序。 您可以根據您的操作系統從https://scala-ide.org/download/sdk.html下載Scala的Eclipse IDE。
c 代碼示例、Open the Scala Eclipse IDE and create new project as;
打開Scala Eclipse IDE并創建新項目;
Select File → New → Scala Project. Enter the project name and click on finish.
選擇文件→新建→Scala項目。 輸入項目名稱,然后單擊完成。
Right click on the project and select New Scala object and enter the object name and click on finish.
scala數組。 右鍵單擊項目,然后選擇New Scala對象,然后輸入對象名稱,然后單擊完成。
Now enter the code in IDE as shown below.
現在,在IDE中輸入代碼,如下所示。
Multiply.scala
Multiply.scala
object Multiply {def main(args: Array[String]) {val m1 = (20, 12, 16, 4)val mul = m1._1 * m1._2 * m1._4println("Result is : " + mul)}
}
scala json,Now run the application as Run As → Scala Project. Below image shows the output produced.
現在,以運行方式→Scala項目的形式運行應用程序。 下圖顯示了產生的輸出。
Tuple.productIterator()
method iterates through all the elements of the tuple.
Tuple.productIterator()
方法遍歷元組的所有元素。
Let us see an example of how to print the student names iterating over the tuple
java代碼? 讓我們看一個示例,該示例如何顯示在元組上迭代的學生姓名
Write the code in scala object Iterate.scala
as;
將代碼寫在scala對象Iterate.scala
中;
object Iterate {def main(args: Array[String]) {val names = ("John","Smith","Anderson","Steve","Rob")names.productIterator.foreach{ i =>println("Value = " + i )}}
}
We are creating a tuple names and use the productIterator method to iterate and print the elements of the tuple.
我們正在創建一個元組名稱,并使用productIterator方法來迭代和打印該元組的元素。
代碼,Now run it as Scala application and see the following output;
現在,將其作為Scala應用程序運行,并看到以下輸出;
Student Names are :
John
Smith
Anderson
Steve
Rob
The Tuple.swap
method is used to swap the elements of the tuple.
Tuple.swap
方法用于交換元組的元素。
object Swap {def main(args: Array[String]) {val id = new Tuple2(12,34)println("Swapped Tuple Id is:"+id.swap)}
}
Output produced will be Swapped Tuple Id is:(34,12)
c++代碼大全? 產生的輸出將被Swapped Tuple Id is:(34,12)
The Tuple.toString()
method concatenates all the elements of the tuple into a string.
Tuple.toString()
方法將元組的所有元素連接成一個字符串。
For Example type the following code in scala object StringConverstion.scala
as
對于示例,在scala對象StringConverstion.scala
鍵入以下代碼為
object StringConversion {def main(args: Array[String]) {val student = new Tuple3(12, "Rob", "IT")println("Concatenated String: " + student.toString())}
}
Scala獲取列表中的前5個元素。Output:
輸出:
Concatenated String: (12,Rob,IT)
級聯字符串:(12,Rob,IT)
A map can be defined as a collection of key/value pairs. Keys are unique but the values need not be unique.
scala數據類型? 映射可以定義為鍵/值對的集合。 鍵是唯一的,但值不必是唯一的。
Maps are of two types mutable and immutable. The difference between mutable and immutable is that when the object is immutable the object itself cannot be changed. Import scala.collection.mutable.Map
to use the mutable map set. By default Scala uses immutable map.
映射具有可變和不可變兩種類型。 可變和不可變之間的區別在于,當對象不可變時,對象本身無法更改。 導入scala.collection.mutable.Map
以使用可變映射集。 默認情況下,Scala使用不可變映射。
Consider an example of map with key as student ids and student names as the value
考慮一個以鍵為學生ID和學生名為值的地圖示例
val student = Map(12 -> "Reena", 13 -> "Micheal" , 14 -> "Peter")
js代碼,Basic Operations on Map:
地圖基本操作 :
The basic methods supported are
支持的基本方法是
keys: Returns an iterator containing each key in a map
scala正則表達式? keys :返回包含映射中每個鍵的迭代器
values: Returns an iterator containing each value in a map
values :返回包含映射中每個值的迭代器
isEmpty: Returns true if the map is empty
isEmpty :如果地圖為空,則返回true
scala list?Consider an example for the basic operations on Map.
考慮一個關于Map的基本操作的例子。
Create the scala object MapOperations.scala
as
將scala對象MapOperations.scala
創建為
object MapOperations {def main(args: Array[String]) {val student = Map(12 -> "Reena", 13 -> "Micheal", 14 -> "Peter")val marks: Map[String, Int] = Map()println("Keys : " + student.keys)println("Values : " + student.values)println("Check if student is empty : " + student.isEmpty)println("Check if marks is empty : " + marks.isEmpty)}
}
Below is the output produced when executed as Scala application.
scala面試題? 以下是作為Scala應用程序執行時產生的輸出。
Keys : Set(12, 13, 14)
Values : MapLike(Reena, Micheal, Peter)
Check if student is empty : false
Check if marks is empty : true
The ++ operator or Map.++() operator is used to concatenate two or more maps but the duplicate keys will be removed.
++運算符或Map。++()運算符用于連接兩個或多個地圖,但是重復的鍵將被刪除。
Consider an example of how to concatenate maps below.
考慮下面的如何連接地圖的示例。
object ConcatMaps {def main(args: Array[String]) {val stud1 = Map(12 -> "Reena", 13 -> "Micheal" , 14 -> "Peter")val stud2 = Map(15 -> "Russel", 16 -> "Mark" , 17 -> "Steve")var student = stud1 ++ stud2println( "stud1 ++ stud2 : " + student )val stu = stud1.++(stud2)println( "stud1.++(stud2)) : " + stu )}
}
Output produced by above program:
上面程序產生的輸出:
stud1 ++ stud2 : Map(14 -> Peter, 13 -> Micheal, 17 -> Steve, 12 -> Reena, 16 -> Mark, 15 -> Russel)
stud1.++(stud2)) : Map(14 -> Peter, 13 -> Micheal, 17 -> Steve, 12 -> Reena, 16 -> Mark, 15 -> Russel)
foreach
loop is used to iterate through all the key and value pairs in a map.
foreach
循環用于遍歷映射中的所有鍵和值對。
For example create a scala object KeyValues.scala as;
例如,創建一個scala對象KeyValues.scala為;
object KeyValues {def main(args: Array[String]) {val stud2 = Map(15 -> "Russel", 16 -> "Mark" , 17 -> "Steve")stud2.keys.foreach{ i => print( "Key = " + i )println(" Value = " + stud2(i) )}}
}
Output:
輸出:
Key = 15 Value = Russel
Key = 16 Value = Mark
Key = 17 Value = Steve
The Map.contains
method to test if a given key exists in the map or not.
Map.contains
方法測試地圖中是否存在給定鍵。
For example create a scala object Keyexists.scala
as;
例如,創建一個scala對象Keyexists.scala
為;
object Keyexists {def main(args: Array[String]) {val stud2 = Map(15 -> "Russel", 16 -> "Mark" , 17 -> "Steve")if( stud2.contains( 15 )){println("Student Id 15 exists with value :" + stud2(15))}else{println("Student Id with 15 does not exist")}if( stud2.contains( 16 )){println("Student Id 16 exists with value :" + stud2(16))}else{println("Student Id 16 does not exist")}if( stud2.contains( 17 )){println("Student Id 17 exists with value :" + stud2(17))}else{println("Student Id 17 does not exist")}if( stud2.contains( 18 )){println("Student Id 18 exists with value :" + stud2(18))}else{println("Student Id 18 does not exist")}}
}
Output:
輸出:
Student Id 15 exists with value :Russel
Student Id 16 exists with value :Mark
Student Id 17 exists with value :Steve
Student Id 18 does not exist
Some of the other useful methods are;
其他一些有用的方法是:
def ++(a: Map[(X, Y)]): Map[X, Y] → Returns a new map containing mappings of this map and those provided by a.
def ++(a:Map [(X,Y)]):Map [X,Y] →返回一個新地圖,其中包含該地圖的映射以及a提供的映射。
def -(e1: X, e2: X, elems: X*): Map[X, Y] → Returns a new map containing all the mappings of this map except mappings with a key equal to e1, e2 or any of elems.
def-(e1:X,e2:X,elems:X *):Map [X,Y] →返回一個新映射,其中包含此映射的所有映射,但鍵等于e1,e2或任何elems的映射除外。
def count(a: ((X, Y)) => Boolean): Int → Counts the number of elements
def count(a:(((X,Y))=>布爾值):Int →計算元素數
def max: (X,Y) → Finds the largest element in the map.
def max:(X,Y) →查找地圖中最大的元素。
def min: (X,Y) → Finds the smallest element in the map
def min:(X,Y) →查找地圖中最小的元素
That’s all for Scala Tuples and Maps, we will look into Option and Iterators in coming post.
Scala元組和Maps就是這樣 ,我們將在以后的文章中介紹Option和Iterators。
翻譯自: https://www.journaldev.com/8079/scala-tuples-and-maps-example
scala代碼示例
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态