scala代码示例

Scala Collections are the containers that hold sequenced linear set of items like List, Set, Tuple, Option, Map etc. Collections may be strict or lazy. The memory is not allocated until they are accessed. Collections can be mutable or immutable.

Scala集合是保存序列线性项(如列表,集合,元组,选项,地图等)的容器。集合可能是严格的或惰性的。 直到访问它们才分配内存。 集合可以是可变的或不可变的。

In this article, let us understand List and Set.

在本文中,让我们了解ListSet

Scala列表 (Scala List)

The elements of the list have same data type. Lists are similar to arrays with two differences that is Lists are immutable and list represents a linked list whereas arrays are flat.

列表中的元素具有相同的数据类型。 列表类似于数组,但有两个区别,即列表是不可变的,列表表示链表,而数组是平面。

List is represented as List[T] where T is the data-type of the elements.

List表示为List[T] ,其中T是元素的数据类型。

Consider an example;

考虑一个例子;

val StudentNames[String] = List("Rohan", "Andreas", "Rob", "John")

Empty list can be created as

空列表可以创建为

val em: List[Nothing] = List()

Two dimensional list can be created as

二维列表可以创建为

val twodim: List[List[Int]] =List(List(1, 0, 0),List(0, 1, 0),List(0, 0, 1))

Scala列表上的基本操作 (Basic Operations on Scala List)

The basic operations include;

基本操作包括:

head: returns first element in the list.

head :返回列表中的第一个元素。

tail: returns all the elements except the first element in the list.

tail :返回列表中第一个元素以外的所有元素。

isempty: returns true if the list is empty.

isempty :如果列表为空,则返回true。

Consider an example for these operations;

考虑这些操作的例子。

object Student {
def main(args:Array[String]) {val names= "Harry" :: ("Adam" :: ("Jill" :: Nil))val age = Nilprintln( "Head of names array : " + names.head )println( "Tail of names array : " + names.tail )println( "Check if names is empty : " + names.isEmpty )println( "Check if age is empty : " + age.isEmpty )}
}

We are creating student object with two lists – names and age. We are invoking the head, tail and empty method on the array names and age.

我们正在创建带有两个列表的学生对象-名称和年龄。 我们正在调用数组名称和年龄的head,tail和empty方法。

Run the output by typing Student.main(null) and you will see below output.

输入Student.main(null)运行输出,您将看到以下输出。

Head of names array : Harry
Tail of names array : List(Adam, Jill)
Check if names is empty : false
Check if age is empty : true

You can also save the above code in Student.scala file and run as

您也可以将以上代码保存在Student.scala文件中,并以

$scalac Student.scala
$scala Student
Head of names array : Harry
Tail of names array : List(Adam, Jill)
Check if names is empty : false
Check if age is empty : true

Scala串联列表 (Scala Concatenating lists)

To concatenate lists we use ::: or List.:::() or concat method to join two or more lists.

要连接列表,我们使用:::或List。:: :()或concat方法来连接两个或多个列表。

Consider an example of how to concatenate the lists

考虑一个如何串联列表的例子

object Country {def main(args:Array[String]) {val country_1 =  List("India","SriLanka","Algeria")val country_2 = List("Austria","Belgium","Canada")val country = country_1 ::: country_2println( "country_1 ::: country_2 : " + country )val cont = country_1.:::(country_2)println( "country_1.:::(country_2) : " + cont )val con = List.concat(country_1, country_2)println( "List.concat(country_1, country_2) : " + con  )}
}

We have created two lists country_1 and country_2. We are concatenating two lists country_1 and country_2 into a single country list using ::: operator. In the second case we are using .::: operator to concat country_1 and country_2 into “cont” list and the second list country_2 data will be first inserted and then country_1 list data is displayed.

我们创建了两个列表country_1和country_2。 我们使用:::运算符将两个列表country_1和country_2连接到一个国家列表中。 在第二种情况下,我们使用。:::运算符将country_1和country_2合并到“连续”列表中,并且将首先插入第二个列表country_2数据,然后显示country_1列表数据。

Finally we use concat method to concatenate country_1 and country_2 into the list “con”.

最后,我们使用concat方法将country_1和country_2连接到列表“ con”中。

Run the above code by typing Country.main(null) and you will see below output.

通过键入Country.main(null)运行以上代码,您将看到以下输出。

country_1 ::: country_2 : List(India, SriLanka, Algeria, Austria, Belgium, Canada)
country_1.:::(country_2) : List(Austria, Belgium, Canada, India, SriLanka, Algeria)
List.concat(country_1, country_2) : List(India, SriLanka, Algeria, Austria, Belgium, Canada)

Scala反向列表顺序 (Scala Reverse List Order)

The List data structure provides List.reverse method to reverse all elements of the list.

List数据结构提供List.reverse方法来反转列表的所有元素。

Consider an example below.

考虑下面的示例。

object Country {def main(args:Array[String]) {val country = List("Denmark","Sweden","France")println("Country List before reversal :" + country)println("Country List after reversal :" + country.reverse)
}
}

Here we are using reverse method to reverse the elements of the country list.

在这里,我们使用反向方法来反转国家/地区列表的元素。

Run the code by typing Country.main(null) and you will see below output.

通过键入Country.main(null)运行代码,您将看到以下输出。

Country List before reversal :List(Denmark, Sweden, France)
Country List after reversal :List(France, Sweden, Denmark)

Scala创建统一列表 (Scala Creating Uniform Lists)

The List.fill() method creates zero or more copies of the same element.

List.fill()方法创建同一元素的零个或多个副本。

Consider an example;

考虑一个例子;

object Student {def main(args: Array[String]) {val name = List.fill(6)("Rehan") println( "Name : " + name  )val id = List.fill(6)(12)         println( "Id : " + id  )}
}

Here we are using fill method and creating the name list with same name “Rehan” for six elements . The id list created with the same id 12 for all the six elements.

在这里,我们使用fill方法并为六个元素创建具有相同名称“ Rehan”的名称列表。 为所有六个元素使用相同的ID 12创建的ID列表。

scala>Student.main(null)Name : List(Rehan, Rehan, Rehan, Rehan, Rehan, Rehan)
Id : List(12, 12, 12, 12, 12, 12)

Scala列表方法 (Scala List Methods)

Some of the other methods supported by List are;

List支持的其他一些方法是:

def distinct: List[X] → Builds a new list from the list without any duplicate elements.

定义:List [X] →从列表中构建一个没有任何重复元素的新列表。

def indexOf(elem: X, from: Int): Int → Finds index of first occurrence of some value in the list after or at some start index.

def indexOf(elem:X,from:Int):Int →在某个起始索引之后或起始索引处查找列表中某个值首次出现的索引。

def length: Int → Returns the length of the list.

def length:Int →返回列表的长度。

def sorted[Y >: X]: List[X] → Sorts the list according to an Ordering.

def sorted [Y>:X]:列表[X] →根据顺序对列表进行排序。

def sum: A → Sums up the elements of this collection.

def sum:A →汇总此集合的元素。

def toString(): String → Converts the list to a string.

def toString():字符串 →将列表转换为字符串。

def min: A → Finds the smallest element.

def min:A →查找最小的元素。

def max A → Finds the largest element.

def max A →查找最大元素。

def lastIndexOf(elem: A, end: Int): Int → Finds index of last occurrence of some value in the list before or at a given end index.

def lastIndexOf(elem:A,end:Int):Int →查找在给定结束索引之前或之列的列表中最后一次出现某个值的索引。

def toMap[X, Y]: Map[X, Y] → Converts this list to a map.

def toMap [X,Y]:Map [X,Y] →将此列表转换为地图。

斯卡拉集 (Scala Set)

Set is a collection of unique elements of the same type. Unlike list Set does not contain duplicate elements. Sets can be mutable or immutable. When the object is immutable the object itself cannot be changed.

Set是相同类型的唯一元素的集合。 与列表不同,Set不包含重复的元素。 集可以是可变的或不可变的。 当对象是不可变的时,对象本身无法更改。

Scala uses immutable set by default. Import scala.collection.mutable.Set to use the mutable set explicitly.

Scala默认使用不可变集。 导入scala.collection.mutable.Set以显式使用可变集合。

For example;

例如;

val country = Set("Russia", "Denmark", "Sweden")

Set of Integer data type can be created as

可以将Integer数据类型集创建为

var id : Set[Int] = Set(4,5,6,7,8,9)

Empty Set can be created as;

空集可以创建为;

var age = Set()

Scala中集合的基本操作 (Basic Operation on Set in Scala)

The basic operations include;

基本操作包括:

head → returns first element of a set.

head →返回集合的第一个元素。

tail → returns all the elements except the first element in the set.

tail →返回集合中第一个元素以外的所有元素。

isempty → returns true if the set is empty else returns false.

isempty →如果集合为空,则返回true,否则返回false。

Consider an example;

考虑一个例子;

object Student {def main(args: Array[String]) {val name = Set("Smith", "Brown", "Allen")val id: Set[Int] = Set()println( "Head of name : " + name.head )println( "Tail of name : " + name.tail )println( "Check if name is empty : " + name.isEmpty )println( "Check if id is empty : " + id.isEmpty )}
}

Here we are creating student object with two sets “names” and “id”. We are doing head, tail and empty operations on these arrays and printing the result.

在这里,我们用两个集合“名称”和“ id”创建学生对象。 我们正在对这些数组进行头,尾和空操作并打印结果。

scala>Student.main(null)Head of name : Smith
Tail of name : Set(Brown, Allen)
Check if name is empty : false
Check if id is empty : true

Scala连接集 (Scala Concatenating Sets)

To concatenate one or more sets use ++ operator or Set.++() method. While adding the sets duplicate items are removed.

要连接一个或多个集合,请使用++运算符或Set。++()方法。 在添加集合时,将删除重复项。

For example;

例如;

object Furniture {def main(args: Array[String]) {val furniture_1 = Set("Sofa", "Table", "chair")val furniture_2 = Set("Bed", "Door")var furniture = furniture_1 ++ furniture_2println( "furniture_1 ++ furniture_2 : " + furniture )var furn = furniture_1.++(furniture_2)println( "furniture_1.++(furniture_2) : " + furn )}
}

We are creating two sets furniture_1 and furniture_2 and concatenating these two sets into furniture and furn using ++ and Set.++ operators.

我们正在创建两组家具_1和furniture_2,并使用++和Set。++运算符将这两组家具连接成furniture和furn。

scala> Furniture.main(null)furniture_1 ++ furniture_2 : Set(Door, Sofa, Bed, Table, chair)
furniture_1.++(furniture_2) : Set(Door, Sofa, Bed, Table, chair)

一组通用值 (Common Values in a Set)

The Set.& method or Set.intersect method can be used to find the common elements in two or more sets.

Set.&方法或Set.intersect方法可用于查找两个或更多集合中的公共元素。

Consider an example below.

考虑下面的示例。

object Numbers {def main(args: Array[String]) {val n1 = Set(11,45,67,78,89,86,90)val n2 = Set(10,20,45,67,34,78,98,89)println( "n1.&(n2) : " + n1.&(n2) )println( "n1.intersect(n2) : " + n1.intersect(n2) )}
}

We are creating two sets of numbers n1 and n2 and finding common elements present in both the sets.

我们正在创建两组数字n1和n2,并找到两组数字中存在的共同元素。

scala> Numbers.main(null)n1.&(n2) : Set(78, 89, 45, 67)
n1.intersect(n2) : Set(78, 89, 45, 67)

一组中的最大和最小元素 (Maximum and Minimum elements in a Set)

The Set.min method is used to find out the minimum and Set.max method to find out the maximum amongst the elements available in a set.

Set.min方法用于查找最小值,而Set.max方法用于查找集合中可用元素中的最大值。

Consider an example;

考虑一个例子;

object Numbers {def main(args: Array[String]) {val num1 = Set(125,45,678,34,20,322,10)println( "Minimum  element in the Set is : " + num1.min )println( "Maximum  element in the Set is : " + num1.max )}
}

We are finding the minimum and maximum numbers in set “num1” using the min and max methods.

我们使用最小和最大方法在集合“ num1”中找到最小和最大数目。

scala> Numbers.main(null)Minimum  element in the Set is : 10
Maximum  element in the Set is : 678

其他有用的Scala设置方法 (Other useful Scala Set Methods)

Some of the Set methods in scala programming are;

Scala编程中的一些Set方法是:

def contains(elem: X): Boolean → Returns true if elem is contained in this set, else returns false.

def contains(elem:X):布尔值 →如果此集合中包含elem,则返回true,否则返回false。

def last: X → Returns the last element.

def last:X →返回最后一个元素。

def product: X → Returns the product of all elements of this immutable set with respect to the * operator in num

def product:X →返回相对于num中的*运算符,此不可变集的所有元素的乘积

def size: Int → Returns the number of elements in this immutable set.

def size:Int →返回此不可变集中的元素数。

def sum: X → Returns the sum of all elements of this immutable set with respect to the + operator in num.

def sum:X →返回相对于num的+运算符,此不可变集合的所有元素的总和。

def toList: List[X] → Returns a list containing all elements of this immutable set.

def toList:List [X] →返回包含此不可变集合的所有元素的列表。

def toSeq: Seq[X] → Returns a sequence containing all elements of this immutable set.

def toSeq:Seq [X] →返回一个包含此不可变集合的所有元素的序列。

def toArray: Array[X] → Returns an array containing all elements of this immutable set.

def toArray:Array [X] →返回包含此不可变集合的所有元素的数组。

def subsetOf(that: Set[X]): Boolean → Returns true if this set is a subset of that, i.e. if every element of this set is also an element of that.

def subsetOf(that:Set [X]):布尔值 →如果此集合是该集合的子集,即该集合的每个元素也是该集合的元素,则返回true。

def mkString: String → Displays all elements of this immutable set in a string.

def mkString:字符串 →在字符串中显示此不可变集合的所有元素。

That’s all for now, we will look into other Scala Collection classes in coming posts.

到此为止,我们将在以后的文章中探讨其他Scala Collection类。

翻译自: https://www.journaldev.com/8068/scala-collections-example

scala代码示例

scala代码示例_Scala集合示例相关推荐

  1. scala代码示例_Scala异常处理示例

    scala代码示例 Scala Exception handling is similar to exception handling in Java. However Scala does not ...

  2. scala代码示例_Scala数组示例

    scala代码示例 Scala supports the array data structure. An array is a fixed size data structure that stor ...

  3. scala代码示例_Scala注释示例

    scala代码示例 Scala Annotations are metadata or extra information added to the program source code. Like ...

  4. scala 连接符_Scala标识符示例教程

    scala 连接符 The names of variables, classes, objects and methods are collectively called Identifiers. ...

  5. scala代码示例_Scala元组和地图示例

    scala代码示例 Scala tuple is a collection of items together of different data types. Scala tuple is immu ...

  6. vantUI所有的弹出层组件(代码、调用、示例) - 集合篇

    文章目录 toast组件 效果图示例: Notify组件(Notify 消息通知.提示) 效果图示例: toast组件 //引入方式 import Vue from 'vue'; import { T ...

  7. xml相关php函数,PHP利用xml常用函数的详细集合示例

    这篇文章主要为大家详细介绍了PHP利用xml常用函数的详细集合示例,具有一定的参考价值,可以用来参考一下. 感兴趣的小伙伴,下面一起跟随512笔记的小玲来看看吧! 1.DOM 函数 a.DOMDocu ...

  8. foreach循环对象集合示例

    foreach循环对象集合示例 mapper.xml mapper.java 实体类定义CompanyRequestDto 实体类定义RegionDto 返回类 CompanyDto service ...

  9. 集合————示例详解

    集合示例: ①.Iterator:迭代器,它是Java集合的顶层接口(不包括 map 系列的集合,Map接口 是 map 系列集合的顶层接口) Object next():返回迭代器刚越过的元素的引用 ...

最新文章

  1. HDU 4869 Turn the pokers(思维+组合公式+高速幂)
  2. Microbiome:宏基因组分箱流程MetaWRAP分析实战和结果解读
  3. 王炸养成记——看Linux 25周年发展变化
  4. 滞后超前校正控制器的设计和matlab仿真 静态速度误差系数为10,自控实验六 基于频域的串联校正控制器设置 - GXUZF.COM - 林澈思的茶...
  5. css 设置背景图片模糊,内容不模糊
  6. 搜索技巧——持续更新
  7. NodeJS中resolve添加地址无效
  8. 厂办大集体改制不签字_许昌二印,磨砂技术被外国觊觎,老工人说烂在肚子里也不外漏...
  9. ajax实现两个aspx跳转,请问ajax执行成功后可以跳转到另一个页面吗?
  10. HALCON 20.11:深度学习笔记(11)---目标检测
  11. Python学习笔记五
  12. 浅析那些带着“主角光环“的泰坦尼克号幸存者(下)
  13. 正在启动文档服务器,正在启动远程服务器
  14. 2021 Mac系统升级后,按大小写键没反应了,切换大小写的灯不亮了
  15. 在Hbuilder X中配置夜神模拟器
  16. 防腐投加器需要加盐吗_什么情况下需要往鱼缸里加盐?盐有什么作用?
  17. 大龄程序员的8种出路
  18. 中软国际软件测试培训中心,中软国际准员工培养计划C++开发/软件测试方向开班典礼...
  19. 讓TQ2440也用上設備樹(1)
  20. SQL Server 和 Oracle 以及 MySQL 的区别

热门文章

  1. (转)SSDTShadow Hook的实现,完整代码
  2. SQL Server 2000企业管理器中MMC无法创建管理单元的解决方法
  3. [转帖] 资本的力量
  4. 末学者笔记--Jenkins+Git+Gitlab+Ansible实现持续集成自动化部署静态网站
  5. sanic set up
  6. [POI2009]石子游戏Kam
  7. JavaSE-22 反射
  8. swift-自定义无限轮播图
  9. exchange EWS 开发随笔二
  10. K_Nearest_Neighbot(knn)方法及其Pyhon 实现