Scala language learning two - collection

Scala Collection

Scala provides a good collection implementations, the collection offers some type of abstraction.

Scala set into a variable (the mutable) and not set (the immutable) becomes
.

  • Variable set: variable length, variable content
  • Immutable collection: immutable length, content is not variable

The variable set may be updated or extended where appropriate. This means that you can modify, add, remove elements of a collection.

Without variable collections, by contrast, will never change. However, you can still simulate add, remove, or update operation. However, these operations will return a new set in each case, while the original set does not change.

Next, we will introduce a collection of several common types of applications:

  1. Scala List (List)

    List feature is its element stored in a linear fashion, repeated collection of objects can be stored.

  2. Scala Set (collection)

    Set is the simplest kind of collection. Objects in the collection is not sorted by a specific manner, and no duplicate object.

  3. Scala Map (map)

    Map is the key for a collection of objects and values ​​of the object mapping, every element of which comprises a pair of key value of objects and objects.

  4. Scala tuple

    A tuple is a set of values for different types of
    examples

The following code is determined, all of the above examples demonstrates the definition set of the type:

// 定义整型 List
val x = List(1,2,3,4)

// 定义 Set
val x = Set(1,3,5,7)

// 定义 Map
val x = Map("one" -> 1, "two" -> 2, "three" -> 3)

// 创建两个不同类型元素的元组
val x = (10, "Runoob")

Scala List (List)

Scala list is similar to the array, all elements are the same type, but they are different: the list is immutable, once defined the value can not be altered, followed by a list of recursive structure (i.e. linked list structure) and the array No.

In Scala list is either empty (empty list indicates Nil) plus either a head element of a list tail.

9 :: List(5, 2) 

:: operator is given head and tail to create a new list

such as

List (9,10,6,4,1)
the first head element 9
tail tail list is 10,6,4,1

Nil represents an empty list

Immutable list

Create a list

In Scala list is either empty (empty list indicates Nil) plus either a head element of a list tail.

val list=List(9,5,2) //创建一个不可变的集合
val list2= :: List(5, 2) // :: 操作符是将给定的头和尾创建一个新的列表
val list3=100:Nil //表示List(100)
val list4=Nil //表示空列表

A list of basic operations

//将 0 插入到 lst1 的前面生成一个新的 List
val lst2 = 0 :: lst1
val lst3 = lst1.::(0)
val lst4 = 0 +: lst1
val lst5 = lst1.+:(0)

//将一个元素添加到 lst1 的后面产生一个新的集合
val lst6 = lst1 :+ 3
val lst0 = List(4,5,6)

//将 2 个 list 合并成一个新的 List
val lst7 = lst1 ++ lst0

//将 lst0 插入到 lst1 前面生成一个新的集合
val lst8 = lst1 ++: lst0

//将 lst0 插入到 lst1 前面生成一个新的集合
val lst9 = lst1.:::(lst0)

// 使用 concat 方法,site1在前,site2在后
fruit = List.concat(site1, site2)
site1在前,site2在后
 
      

list.count    //返回个数

list.filter(x=>x>=3)    //过滤,过滤大于等于3的元素,生成一个新的集合

list.sorted()   //默认升序排序,生成一个新的集合

wps=List(("a",1),("c",3))
wps.sortBy(t=>-t._2) //根据什么排序升序,参数为函数

wps.sortWith((x,y)=>x._2>y._2)     //根据需求排序,有点像compare to,参数是boolean

grouped()让组内的多少分一组,比如两个分一组
list.grouped(2)//List(List(1,2),List(3,4),List(1,2))
看到55分


}

A list of commonly used methods

list=List(3,5,1)
fold(初始值)(叠加的函数)
list.fold(0)((x,y)=>x+y)


/*计算过程
*0+3//0是初始值
*(3+5)
*(8+1)=9
*结果为9,9+3+5+1
*
*foldLeft
*foldRight
*只是整合的方向不停
*第一个下划线代表初始值,第二个代表集合中操作的元素
*简写 list.fold(0)(_+_)
*
*/




-----------------------------------------------------------
list.reduce((x,y)=>x+y)

也是整合
---------------------------------------
 List.union(list2)

求两个集合的并集

-------------------------- 
交集
list.intersect(list2)
——————————————
差集
list.diff(list2 )

-----------------
list(0,8,6)
list2(3,5,1)
list.zip(list2)  //对应位置组成元组
//得结果
//list((3,0),(5,8),(1,6))

r.map(x=>(x._1+x._2)) //元组相加


----------------------------
list2.mkString("|")
//生成字符串,可指定分割符
0|8|6|3
-----------------------
list.length()
list.size()
//求长度,一样的
----------------------------------
//列表截取 前闭后开
list.slice(1,3)
list.slice(1,list.length-1)




Variable list

// If you want to use a variable array, you need to import import scala.collection.mutable.ListBuffer package

import scala.collection.mutable.ListBuffer

object MutListTest extends App{

//构建一个可变列表, 初始有 3 个元素 1,2,3
val lst0 = ListBuffer[Int](1,2,3)

//创建一个空的可变列表
val lst1 = new ListBuffer[Int]

//向 lst1 中追加元素, 注意: 没有生成新的集合
lst1 += 4
lst1.append(5)

//将 lst1 中的元素最近到 lst0 中, 注意: 没有生成新的集合
lst0 ++= lst1

//将 lst0 和 lst1 合并成一个新的 ListBuffer 注意: 生成了一个集合
val lst2= lst0 ++ lst1
//将元素追加到 lst0 的后面生成一个新的集合
val lst3 = lst0 :+ 5
}

Scala Set (collection)

Scala Set (collection) is not repeated collection of objects, all elements are unique.

Scala variable set into a set and immutable.

By default, the Scala is an immutable set of use if you want to use the variable collection, you need to reference scala.collection.mutable.Set package.

The default reference scala.collection.immutable.Set, immutable collection of examples are as follows:

A set of basic operations of the variable

import scala.collection.immutable.HashSet   //导入包

val set1 = new HashSet[Int](1,3,4)   //生成一个可变的set

set1.add(5)  //添加元素
set+=(3) //添加元素
set1.remove(1)  //移除元素
set-=(3)  //移除元素
set ++=Set(0,9)    //拼接两个Set




// 查找集合中最大与最小元素
min = num.min 
max=num.max 

A set of basic operations immutable

al set =Set(1,2,3) //生成一个不可变的set

//方法类似,只是不可变,需要新生成一个set

Scala Map (map)

  • Map (mapping) is an iterative value pair (key / value) structure.

  • All values ​​can be obtained through the key.

  • Map the key is unique.

  • Map is also called a hash table (Hash tables).

  • Map There are two types of variable and non-variable, except that the variable object can modify it without mutable objects may not.

  • By default Scala immutable Map. If you need to use a variable collection, you need to explicitly introduce import scala.collection.mutable.Map class

  • In Scala you can use both variable and immutable Map, immutable directly using Map, variable use mutable.Map. The following examples demonstrate the application of immutable Map:

Demo:

// 空哈希表,键为字符串,值为整型
var A:Map[Char,Int] = Map()

// Map 键值对演示
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")

When you define Map, need to define the type of key-value pairs. If you need to add the key-value pairs, the + sign may be used, as follows:

A += ('I' -> 1)
A += ('J' -> 5)
A += ('K' -> 10)
A += ('L' -> 100)

Mapping operation immutable

定义一个定长的映射
val mp=Map[String,Int]"a"->1,"b"->2)

Variable mapping operation

import scala.collection.mutable
val map1 =  mutable.HashMap[String, Int]()


//向 map 中添加数据
map1("spark") = 1
map1 += (("hadoop", 2))
map1.put("storm", 3)

println(map1)

// 取值 get getOrElse()
//从 map 中移除元素
map1 -= "spark"
map1.remove("hadoop")

println(map1)


map1.get("hadoop").get  //取value,如果是null,则异常
map1.get("hadoop",0).getOrElse  //取value,如果没有就传默认值,可设定,这里是0
 map1.MapValue(t=>t+100))   //对map的value进行操作,然后返回值是操作后的map
 //区别于
 map1.map(x=>x._2+100)

Scala tuple

Scala tuples fixed number of items together, so that they can be passed as a whole.
With different arrays or lists, tuples can accommodate different types of objects, but they are immutable.
Tuples can put any data type

Currently the maximum tuple length Scala support is 22.

The definition of a tuple

The following examples are defined in the tuple three elements, respectively corresponding to the type [Int, Double, java.lang.String].

In addition, we can also be defined in the following ways:

val t = (1, 3.14, "Fred")  
val t = new Tuple3(1, 3.14, "Fred")

Access tuple of elements

We can use the first access element t._1, t._2 access the second element, as follows:

println(t._2) // 访问元组总的第二个元素

Dual-tuple

// 对偶元组
val tuple2 = (1, 3)
// 交换元组的元素位置, tuple2 没有变化, 生成了新的元组
val swap = tuple2.swap

Case 2 scala word in mind to achieve

Analysis:
Step 1: map (x => ( x, 1) // element into the tuple (word 1)
Step 2:. GroupBy (X = X 1) // make first tuple element according grouping
step. 3: mapValue (T => t.foldLeft (0) (
+ . 2)) to map the extracted value, then the value is the array element from the group consisting of, underline represents a first initial value, the second representative element the second group of elements, i.e. the count, then t.foldLeft (0) ( + ._2) tuple adding the second element, the number of additions is

arr.flatMap(_.split(" ")).map(x=>(x,1).groupBy(x=x._1).mapValue(t=>t.foldLeft(0)(_+_._2))
//返回值Map(scala->1,holo->1,lin->2)
Published 44 original articles · won praise 0 · Views 862

Guess you like

Origin blog.csdn.net/heartless_killer/article/details/103328330