Collection types in Scala

----------content--------------------------------------- ------------------

1. Scala introduction and installation

2. Introduction to Scala syntax

3. Scala functions

4. Collection types in Scala

-------------------------------------------------------------------------------------------------------------

Collection types in Scala

    Scala provides a nice set of collection implementations that provide some abstraction for collection types. Scala collections are divided into immutable collections and mutable collections.

    Scala's collection types (collections) cover the following types:

    Array (Array), linked list (List), Set, Map, Tuple.

1. Array

    For the use of arrays, if we want to call the methods provided by the array, we need to use import Array._ to import the package.

1. array declaration

    1. Array Array is divided into fixed-length and variable-length arrays. The later commonly used type is fixed length (Array).

    2. Scala's generic declaration is defined using [], which is different from Java's <>.

    3. Scala operates Array by subscripting, and uses () to operate, which is different from Java's [index].

    Fixed-length array: scala.collection.immutable.Array, once declared, the length is immutable.

    Variable-length array: scala.collection.mutable.ArrayBuffer, dynamic array.

    example:

  //创建一个定长数组,一旦声明,长度不可变
  val a1=Array(1,2,3,4)
  //创建一个变长数组
  val a2=ArrayBuffer(1,2,3)
  //创建数组,并指定范围
  val a3=Array[Int](1,2,3)
  //通过下标操作数组
  a1(1)
  //> res0: Int = 2
  //创建一个长度为3的定长数组
  //注意,需要指定泛型类型。
  val a4=new Array[Int](3)

2. Assignment and retrieval

1> Assignment

    Assignment method 1: Use a for loop to assign values ​​to the array var1.

    Assignment method 2: Assign value to a variable-length array. Note: The variable-length array provides the append method for assignment and implicitly changes the length of the array.

    Example:

  //赋值
  for(i<-0 to a4.length-1)a4(i)=i
  a4
  //> res1: Array[Int] = Array(0, 1, 2)
  val v5=new ArrayBuffer[Int](3)
  //变长数组可以通过append赋值
  for(i<-0 to 10)v5.append(i)

2> value

 Value method 1: Obtain the value according to the subscript of the array.

 Value method 2: Use the for loop to obtain the value.

 Value method three: use the higher-order function foreach.

    Example:

  //通过下标操作数组
  a1(1);a1(2);a1(0)
  //利用for循环获取值
  for (i <- a1) println(i)
  a1.foreach{x=>println(x)}

3. function

1>concat

    To combine the results of multiple arrays together, import Array._.

    When merging, the types of the arrays must be the same, either all of them are fixed-length or all variable-length, and the combination between fixed-length and variable-length cannot be performed.

    Example:

  val v6 = Array(1, 2, 3)
  val v7 = Array(4, 5, 6)
  //合并多个定长数组
  val v8 = Array.concat(v6, v7)
  //合并多个变长数组
  val v9 = ArrayBuffer.concat(v5, a2)

2>range

    Creates an array of intervals, with headers and tails.

    Example:

  //创建区间数组
  val v10 = Array.range(0, 5)
  //创建区间数组,并指定步长为2
  val v11 = Array.range(0, 5, 2)
  val v12 = ArrayBuffer.range(0, 5)

3>iterate

    Returns an array containing a function repeatedly applied to the initial value.

    Example:

  //iterate将匿名函数应用到初始值,并返回指定长度的数组
  val v13 = Array.iterate(1, 5)(x => x + 1)
  val v131 = Array.iterate(1, 5)(_ * 2)

4>tabulate

    Returns an array of the specified length, each array element is the return value of the specified function, starting from 0 by default.

    Example:

  //tabulate是将匿名函数应用到数组下标的函数,并返回指定长度的数组。
  val v14 = Array.tabulate(5)(_ + 1)
  val v141 = Array.tabulate(5)(_ * 2)

5>sum

    Sum, which sums the elements in the array.

    Example:

val v6 = Array(1, 2, 3)
//求和
v6.sum

6>min

    minimum value.

    Example:

  val v6 = Array(1, 2, 3)
  //最小值
  v6.min

7>max

    maximum value.

    Example:

  val v6 = Array(1, 2, 3)
  //最大值
  v6.max

8>quickSort

    Sort, sort the array elements.

    Call format:

    scala.util.Sorting.quickSort(Array)

    Example:

	val v20=Array(1,4,3,2,6)
	scala.util.Sorting.quickSort(v20)
	v20

9>drop

    delete.

    Example:

  //去除头部n个元素,并返回去除后的数组
  v6.drop(1)
  //去除尾部n个元素,并返回去除后的数组
  v6.dropRight(1)

10>take

    Extract the first n elements and return an array of the extracted elements.

    Example:

  //取出头n个元素,并返回取出的元素数组。
  v6.take(1)
  //取出末尾n个元素,并返回取出的元素数组。
  v6.takeRight(1)

11>foreach

    Loop through.

    Example:

  v6.foreach { x => println(x) }
  v6.foreach { println(_) }

12>map

    Change the type of the collection, the form or data of the elements, and return a new collection. This method does not change the number of elements in the collection, only the value and form.

    Example:

  val v15 = v6.map { x => x + 1 }
  v6.map { _ * 1.0 }
  v6.map { x => x.toDouble }

  val v17 = Array("hello world", "hello hadoop")
  v17.map { _.split(" ") }

2. List linked list

1. Declaration list

    The underlying data structure implemented with linked lists.

    Fixed-length list: scala.collection.immutable.List, once declared, the length is immutable.

    Variable-length list: scala.collection.mutable.ListBuffer, variable-length list.

    Example:

  //声明一个定长List
  val l1=List(1,2,3,4)
  //声明一个变长List
  val l2=ListBuffer(1,2,3)
  val l3=List[Int](1,2,3)
  val l4=1::2::3::Nil
  //声明一个定长空List
  val l5=List[Nothing]()

2. value

    Subscript acquisition.

    Example:

//通过下标取值
l9(0)
//> res9: Int = 4

3. function

1>head

    Returns the head element.

    Example:

//返回头元素
l1.head
//> res0: Int = 1

2>tail

    Remove the head element and return a List of remaining elements, equivalent to drop(1).

    Example:

l1.tail
//> res1: List[Int] = List(2, 3, 4)
l1.drop(1)
//> res2: List[Int] = List(2, 3, 4)

3>isEmpty

    Determine if it is empty.

    Example:

l1.isEmpty
//> res3: Boolean = false
l5.isEmpty
//> res4: Boolean = true

4> Merge

:::

    When splicing List, the List type needs to be consistent.

    Example:

l1:::l3
//> res5: List[Int] = List(1, 2, 3, 4, 1, 2, 3)

concat

    Example:

List.concat(l1,l3)
//> res6: List[Int] = List(1, 2, 3, 4, 1, 2, 3)

5>fill

    Fill with the specified data and return a new List.

    Example:

val l6=List.fill(5)("a")
//> l6  : List[String] = List(a, a, a, a, a)

6>tabulate

    Creates an array of size n, and the subscript of the array element is changed to the element of the current subscript according to the incoming rules.

    Example:

val l7=List.tabulate(5)(_*2)
//> l7  : List[Int] = List(0, 2, 4, 6, 8)

7>reverse

    Invert, and return a new List

val l8=l1.reverse
//> l8  : List[Int] = List(4, 3, 2, 1)

8> Add

+:

    Adds elements from the left, and returns a new List.

    Example:

val l9=List(4,5,6)
//> l9  : List[Int] = List(4, 5, 6)
//从左侧添加元素,并返回新的List
3+:l9
//> res7: List[Int] = List(3, 4, 5, 6)

:+

    Adds elements from the right, and returns a new List.

    Example:

l9:+7
//> res8: List[Int] = List(4, 5, 6, 7)

9>contains

    Check to see if an element is included.

    Example:

l9.contains(4)
//> res10: Boolean = true

10>copyToArray

    Copies elements into Array.

    Example:

var a1=new Array[Int](3)
//> a1  : Array[Int] = Array(0, 0, 0)
l9.copyToArray(a1, 0, l9.length)
a1
//> res11: Array[Int] = Array(4, 5, 6)

11> Type conversion

toArray

    Convert to array type.

    Example:

l9.toArray
//> res12: Array[Int] = Array(4, 5, 6)

toList

    Converted to a linked list.

    Example:

a1.toList
//> res13: List[Int] = List(4, 5, 6)

12>distinct

    Remove duplicates and return a new List.

    Example:

val l10=List(1,1,1,2,2,2,3,4,4,4)
l10.distinct
//> res14: List[Int] = List(1, 2, 3, 4)

13>exists

    Check whether the element exists by an anonymous function.

    Example:

l10.exists { x => x%2==0 }
//> res15: Boolean = true
l10.exists {	_%2==0 }
//> res16: Boolean = true
val l11=List(1,2,3,4,5,6)
//> l11  : List[Int] = List(1, 2, 3, 4, 5, 6)
l11.exists { x => x%2==0&&x>4 }
//> res17: Boolean = true

14> filter

    filter.

    Example:

l11.filter { x => x>3 }
//> res18: List[Int] = List(4, 5, 6)
l11.filter { _>3 }
//> res19: List[Int] = List(4, 5, 6)
l11.filter { x => x>3&&x%2==0 }
//> res20: List[Int] = List(4, 6)

15>indexOf

    Finds the position of the first occurrence of the specified element and returns the position.

    Example:

l10.indexOf(1, 0)
//> res21: Int = 0
l10.indexOf(2, 3)
//> res22: Int = 3
val l12=List(1,2,3,1,2,3)
//> l12  : List[Int] = List(1, 2, 3, 1, 2, 3)
l12.indexOf(1, 1)
//> res23: Int = 3

16>intersect

    Gets the intersection, and returns a List of values.

    Example:

val l13=List(1,2,3)
val l14=List(3,4,5)
l13.intersect(l14)
//> res24: List[Int] = List(3)
//通过类型转换去使用API
val a2=Array(1,2,3)
val a3=Array(2,3,4)
a2.toList.intersect(a3.toList).toArray
//> res25: Array[Int] = Array(2, 3)

17>last

    Get the last element.

    Example:

l13.head
//> res26: Int = 1
l13.last
//> res27: Int = 3

18>length

    Array length.

    Example:

l13.length
//> res28: Int = 3

19>map

l13.map { x => x*2 }
//> res29: List[Int] = List(2, 4, 6)
l13.map { _*2 }
//> res30: List[Int] = List(2, 4, 6)

20>mkString

    Returns the elements in the collection with the specified separator to form a string.

    Example:

l13.mkString
//> res31: String = 123
l13.mkString(",")
//> res32: String = 1,2,3

21> Sort

sorted

    Sorts in ascending order and returns a List.

    Example:

val l15=List(2,1,4,7,6)
l15.sorted
//> res33: List[Int] = List(1, 2, 4, 6, 7)
//降序
l15.sorted.reverse
//> res34: List[Int] = List(7, 6, 4, 2, 1)

sortWith

//降序
l15.sortWith{(a,b)=>a>b}
//> res35: List[Int] = List(7, 6, 4, 2, 1)
l15.sortWith{_>_}
//> res36: List[Int] = List(7, 6, 4, 2, 1)
//升序
l15.sortWith{(a,b)=>a<b}
//> res37: List[Int] = List(1, 2, 4, 6, 7)

sortBy

//重点掌握此排序
l15.sortBy{x=>x}
//> res38: List[Int] = List(1, 2, 4, 6, 7)
l15.sortBy{+_}
//> res39: List[Int] = List(1, 2, 4, 6, 7)
l15.sortBy{x=> -x}
//> res40: List[Int] = List(7, 6, 4, 2, 1)
  l15.sortBy{-_}
//> res41: List[Int] = List(7, 6, 4, 2, 1)

22>reduceLeft

l15.reduceLeft(_+_)

3、Set

    A Scala Set is a collection of objects without repetition, all elements are unique. Scala collections are divided into mutable and immutable collections.

    By default, Scala uses immutable collections, if you want to use mutable collections, you need to refer to the scala.collection.mutable.Set package. Default references to scala.collection.immutable.Set.

1. declare Set

//声明定长Set
val s1=Set(1,2,3)
//声明变长Set
val s2=scala.collection.mutable.Set(2,3,4)
val s3=Set(1,1,1,2,2,2)
//> s3  : scala.collection.immutable.Set[Int] = Set(1, 2)

2. function

1> Get the intersection

  //取交集
  val s4=Set(1,2,3)
  val s5=Set(3,4,5)
  s4.&(s5)
//> res0: scala.collection.immutable.Set[Int] = Set(3)
  s4&s5
//> res1: scala.collection.immutable.Set[Int] = Set(3)

2> Get the difference

&~

//取差集
s4 &~ s5
//> res2: scala.collection.immutable.Set[Int] = Set(1, 2)
s5 &~ s4
//> res4: scala.collection.immutable.Set[Int] = Set(4, 5)

diff

  s4.diff(s5)
//> res3: scala.collection.immutable.Set[Int] = Set(1, 2)
  s5.diff(s4)
//> res5: scala.collection.immutable.Set[Int] = Set(4, 5)

3>++

    merge.

  //合并
 	s4 ++ s5
//> res6: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)

4>count

    Returns the number of elements that satisfy the anonymous function.

  s4.count { x => x>1 }
//> res7: Int = 2
  s4.count(_>1)
//> res8: Int = 2

5> splitAt

    Cut into two sets, one of which satisfies the specified number. The returned data type is Tuple.

  val s6=Set(1,2,3,4,5,6,7)
//> s6  : scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 7, 3, 4)
  s6.splitAt(4)

4. Map mapping

    Map (map) is an iterable key-value pair (key/value) structure. All values ​​can be retrieved by key.

    The keys in a Map are all unique. Maps are also called hash tables.

    Map has two types, mutable and immutable, the difference is that mutable objects can modify it, while immutable objects cannot.

    Scala uses immutable Maps by default. If you need to use mutable collections, you need to import scala.collection.mutable.Map class explicitly

    In Scala you can use both mutable and immutable Map, immutable use Map directly, mutable use mutable.Map.

1. Declare Map

  //声明定长map
  val m1=Map("k1"->1,"k2"->2,"k3"->3)
  //声明变长map
  val m2=scala.collection.mutable.Map("k1"->1,"k2"->2,"k3"->3)

2. function

1>+=

    += adds elements, can only be used for variable-length maps.

  m2+=("k4"->4)
//> res0: Demo06.m2.type = Map(k2 -> 2, k4 -> 4, k1 -> 1, k3 -> 3)

2>keys

    Get all keys.

  val m3=Map("rose"->23,"tom"->25,"jim"->30)
  //获取所有key
  m3.keys
//> res1: Iterable[String] = Set(rose, tom, jim)

  //获取所有的key并返回一个迭代器
  m3.keys.foreach(x=>println(x))

3>values

    Get all values.

  m3.values
  //> res2: Iterable[Int] = MapLike(23, 25, 30)
  //获取所有的value,并返回一个迭代器
  m3.values.foreach(println(_))

4>++

    merge.

  val m4=Map[String,Int]("k1"->1,"k2"->2)
  val m5=Map[String,Int]("k3"->3,"k4"->4)
  m4 ++ m5
//> res3: scala.collection.immutable.Map[String,Int] = Map(k1 -> 1, k2 -> 2, k3 -> 3, k4 -> 4)

5>contains

    Whether to include the specified key.

  m4.contains("k1")
//> res4: Boolean = true

6>get

    Get the value of the specified key and return some type

  m4.get("k1")
//> res5: Option[Int] = Some(1)
  //操作some类型,需要通过getOrElse来取值
  //如果查找一个不存在的key,会返回指定的默认值,以避免报错
  m4.get("k3").getOrElse(0)
//> res6: Int = 0

7>apply

    apply takes the value directly through the key, and reports an error if the key does not exist.

  m4.apply("k1")
//> res7: Int = 1

8>clear

    Clear the map. Only variable-length maps have this method.

  m2.clear()

9> filter

    filter.

  val m6=Map(1->"tom",2->"rose",3->"jim",4->"jary")
  m6.filter(x=>x._1>2)
//> res8: scala.collection.immutable.Map[Int,String] = Map(3 -> jim, 4 -> jary)
  m6.filter{case(k,v)=>k>2}
//> res9: scala.collection.immutable.Map[Int,String] = Map(3 -> jim, 4 -> jary)

10>size

    returns the number of elements

  m6.size

5. Tuple tuple

    Like lists, tuples are immutable, but unlike lists, tuples can contain elements of different types. A tuple of values ​​is formed by enclosing the individual values ​​in parentheses.

1. Statement Tuple

    Use () to declare tuples. Tuples are the most flexible data structure.

 

  //声明元组
  val t1=(1,2,3,4,5)
  val t2=(1,"hello",List(1,2,3),Array(2,3))
  val t3=((1,2),("rose",23),(3,4))
  val l1=List(1,2,(4,5))

2. value

    The value of the tuple is ._index (the value of index starts from 1)

    Example:

//元组取值,是从1开始的。
  t1._1
//> res0: Int = 1
  t1._3
//> res1: Int = 3
  t3._2._1
//> res2: String = rose

application:

  val a1=Array("hello","world","hello","hadoop")
  //要求,将a1里的元素改为:Array(("hello",1),("world",1)……)
  val a2=a1.map { x => (x,1) }
  //> a2  : Array[(String, Int)] = Array((hello,1), (world,1), (hello,1), (hadoop, 1))
  //要求:操作a2还原回去
  a2.map(x=>x._1)

Previous: Scala functions

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325386975&siteId=291194637