Scala数组和集合

一、scala数组

    数组定义1: var arr = new Array[String](3)
    String:存储的元素类型
    3:存储3个元素
    添加元素: arr(1) = "hello"
    数组定义2: val arr1 = Array[Int](1,2,3,4,5,6)
    改变内容:arr1(1) = 18
    添加元素:arr1 += 22 长度不可以改变

二、数组方法

1、map(映射)

    映射: 2 4 6
    映射关系:f(x) = x*5
    对应映射关系:10 20 30

例:

scala> var arr = Array(1,2,3)
arr: Array[Int] = Array(1, 2, 3)

scala> arr.map((x: Int) => x * 10)
res12: Array[Int] = Array(10, 20, 30)

scala> arr
res13: Array[Int] = Array(1, 2, 3)

scala> res12
res14: Array[Int] = Array(10, 20, 30)

2、flatten(扁平化操作)

scala> var arr = Array("hello Beijing","hello China")
arr: Array[String] = Array(hello Beijing, hello China)

scala> arr.length
res6: Int = 2

scala> arr.map(_.split(" "))
res7: Array[Array[String]] = Array(Array(hello, Beijing), Array(hello, China))

scala> arr.map(_.split(" ")).flatten
res8: Array[String] = Array(hello, Beijing, hello, China)

3、flatMap(相当于先map操作再flatten)

scala> arr
res9: Array[String] = Array(hello Beijing, hello China)

scala> arr.flatMap(_.split(" "))
res10: Array[String] = Array(hello, Beijing, hello, China)

4、foreach(遍历数组中的元素)

scala> res10.foreach(x => println(x))
hello
Beijing
hello
China

scala>

5、GroupBy(分组)

scala> arr
res13: Array[String] = Array(hello Beijing, hello China)

scala> arr.flatMap(_.split(" ")).groupBy(x => x)
res14: scala.collection.immutable.Map[String,Array[String]] = Map(Beijing -> Array(Beijing), China -> Array(China), hello -> Array(hello, hello))

//Scala简易WordCount
scala> arr.flatMap(_.split(" ")).groupBy(x => x).map(x => (x._1,x._2.length))
res16: scala.collection.immutable.Map[String,Int] = Map(Beijing -> 1, China -> 1, hello -> 2)

6、sortBy(排序)

scala> arr
res13: Array[String] = Array(hello Beijing, hello China)
//正序
scala> arr.flatMap(_.split(" ")).groupBy(x => x).map(x => (x._1,x._2.length)).toList.sortBy(x => x._2)
res18: List[(String, Int)] = List((Beijing,1), (China,1), (hello,2))
//倒序
scala> arr.flatMap(_.split(" ")).groupBy(x => x).map(x => (x._1,x._2.length)).toList.sortBy(x => -x._2)
res19: List[(String, Int)] = List((hello,2), (Beijing,1), (China,1))

三、集合

    scala集合有两种类型:可变mutable
    不可变Immutable
    val b = List(2,4,6)
    不可变集合:内容不可变(数组内容可改变)
    长度不可变
    可变集合:
    注意:需要导包
    import scala.collection.mutable._
    val buff = ArrayBuffer(2,3,4)
    内容可变: buff(1) = 300
    长度可变:buff += 200

例:

scala> val s = List(1,2,3)
s: List[Int] = List(1, 2, 3)

scala> s(1) = 8
<console>:13: error: value update is not a member of List[Int]
       s(1) = 8
       ^

scala> val b = List(2,3,4)
b: List[Int] = List(2, 3, 4)

scala> b += 20
<console>:13: error: value += is not a member of List[Int]
       b += 20
         ^

scala> import scala.collection.mutable._
import scala.collection.mutable._

scala> val buff = ArrayBuffer(2,3,4)
buff: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(2, 3, 4)

scala> buff += 200
res23: buff.type = ArrayBuffer(2, 3, 4, 200)

scala> buff(1) = 300

scala> buff
res25: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(2, 300, 4, 200)

scala> scala.collection.mutable.
AVLIterator            History               PriorityQueueProxy
AVLTree                ImmutableMapAdaptor   Publisher
AbstractBuffer         ImmutableSetAdaptor   Queue
AbstractIterable       IndexedSeq            QueueProxy
AbstractMap            IndexedSeqLike        ResizableArray
AbstractSeq            IndexedSeqOptimized   RevertibleHistory
AbstractSet            IndexedSeqView        Seq
AnyRefMap              Iterable              SeqLike
ArrayBuffer            LazyBuilder           Set
ArrayBuilder           Leaf                  SetBuilder
ArrayLike              LinearSeq             SetLike
ArrayOps               LinkedEntry           SetProxy
ArraySeq               LinkedHashMap         SortedSet
ArrayStack             LinkedHashSet         Stack
BitSet                 LinkedList            StackProxy
Buffer                 LinkedListLike        StringBuilder
BufferLike             ListBuffer            Subscriber
BufferProxy            ListMap               SynchronizedBuffer
Builder                LongMap               SynchronizedMap
Cloneable              Map                   SynchronizedPriorityQueue
DefaultEntry           MapBuilder            SynchronizedQueue
DefaultMapModel        MapLike               SynchronizedSet
DoubleLinkedList       MapProxy              SynchronizedStack
DoubleLinkedListLike   MultiMap              Traversable
FlatHashTable          MutableList           TreeSet
GrowingBuilder         ObservableBuffer      Undoable
HashEntry              ObservableMap         UnrolledBuffer
HashMap                ObservableSet         WeakHashMap
HashSet                OpenHashMap           WrappedArray
HashTable              PriorityQueue         WrappedArrayBuilder

scala> val lb = scala.collection.mutable.ListBuffer(11,22,33)
lb: scala.collection.mutable.ListBuffer[Int] = ListBuffer(11, 22, 33)

scala> lb(1) = 334

scala> lb += 222
res27: lb.type = ListBuffer(11, 334, 33, 222)

scala> lb
res28: scala.collection.mutable.ListBuffer[Int] = ListBuffer(11, 334, 33, 222)

四、长度可变的数组

    创建长度可变数组:
    val ab = scala.collection.mutable.ArrayBuffer(2,3,4)
    长度可变:
    ab += 440

五、Seq序列

    不可变的序列
    在scala中列表要么为空(Nil表示空列表)
    head元素上加上一个tail列表

    head:取头元素
    tail:取尾元素(除了头全是尾)

    5::Nil 空列表的头加入一个元素
    1::2::3::Nil 空列表前加入三个元素1,2,3

    + 字符串的拼接
    ++ 两个集合相加
    ++: 合并集合
    .+: 头部追加元素
    :+ 尾部追加元素
    ::: 两个集合相加
    count 统计个数
    filter 过滤
    sortBy 排序
    sortWwith 排序
    grouped 分组
    fold 折叠
    foldLeft 左折叠
    foldRight 右折叠
    reduce 聚合
    aggregate 先局部聚合再全局聚合
    zip 拉链
    sum 求和

例:

scala> import scala.collection.immutable._
import scala.collection.immutable._

scala> Nil
res30: scala.collection.immutable.Nil.type = List()

scala> val l = List(2,1,5,8,9)
l: List[Int] = List(2, 1, 5, 8, 9)

scala> l.head
res31: Int = 2

scala> l.tail
res32: List[Int] = List(1, 5, 8, 9)

scala> 5::Nil
res33: List[Int] = List(5)

scala> val s = Nil
s: scala.collection.immutable.Nil.type = List()

scala> 3::s
res34: List[Int] = List(3)

scala> s
res35: scala.collection.immutable.Nil.type = List()

scala> res34
res36: List[Int] = List(3)

scala> 1::2::3::Nil
res37: List[Int] = List(1, 2, 3)

scala> val ll = List(3,4,5)
ll: List[Int] = List(3, 4, 5)

scala> ll + "a"
res38: String = List(3, 4, 5)a

scala> ll
res39: List[Int] = List(3, 4, 5)

scala> ll ++ List(6,7)
res40: List[Int] = List(3, 4, 5, 6, 7)

scala> ll ++:List(6,7,8)
res41: List[Int] = List(3, 4, 5, 6, 7, 8)

scala> ll
res42: List[Int] = List(3, 4, 5)

scala> ll.+:(55)
res43: List[Int] = List(55, 3, 4, 5)

scala> ll:+(66)
res44: List[Int] = List(3, 4, 5, 66)

scala> ll
res45: List[Int] = List(3, 4, 5)

scala> val lll = List(33,44)
lll: List[Int] = List(33, 44)

scala> ll::lll
res46: List[Any] = List(List(3, 4, 5), 33, 44)

scala> ll:::lll
res47: List[Int] = List(3, 4, 5, 33, 44)

scala> ll
res48: List[Int] = List(3, 4, 5)

scala> ll.count(x => x>4)
res49: Int = 1

scala> ll.count(x => x>=4)
res50: Int = 2

scala> ll.filter(x => x >+5)
<console>:19: error: value >+ is not a member of Int
       ll.filter(x => x >+5)
                        ^

scala> ll.filter(x => x >=5)
res52: List[Int] = List(5)

scala> ll.filter(x => x >= 5)
res53: List[Int] = List(5)

scala> val ls = List(6,2,1,3,8,7)
ls: List[Int] = List(6, 2, 1, 3, 8, 7)

scala> ls.sortBy(x => x)
res54: List[Int] = List(1, 2, 3, 6, 7, 8)

scala> ls.sortBy(x => -x)
res55: List[Int] = List(8, 7, 6, 3, 2, 1)

scala> ls
res56: List[Int] = List(6, 2, 1, 3, 8, 7)

scala> val sw = List(("h",2),("r",1),("m",4))
sw: List[(String, Int)] = List((h,2), (r,1), (m,4))

scala> sw.sortBy(x => x._2)
res57: List[(String, Int)] = List((r,1), (h,2), (m,4))

scala> sw.sortWith((x,y) => x._2 > y._2)
res58: List[(String, Int)] = List((m,4), (h,2), (r,1))

scala> val sw = List(("h",2),("r",2),("m",4))
sw: List[(String, Int)] = List((h,2), (r,2), (m,4))

scala> sw.groupd(2)
<console>:19: error: value groupd is not a member of List[(String, Int)]
       sw.groupd(2)
          ^

scala> sw.grouped(2)
res60: Iterator[List[(String, Int)]] = non-empty iterator

scala> sw.grouped(2).toList
res61: List[List[(String, Int)]] = List(List((h,2), (r,2)), List((m,4)))

scala> val l2 = List(1,3,4)
l2: List[Int] = List(1, 3, 4)

scala> l2.fold(0)((x,y) => x+y)
res62: Int = 8

scala> l2.fold(1)((x,y) => x+y)
res63: Int = 9

scala> l2.fold(2)((x,y) => x+y)
res64: Int = 10

scala> ls.fold(2)((x,y) => x-y)
res65: Int = -25

scala> ls
res66: List[Int] = List(6, 2, 1, 3, 8, 7)

scala> l2.fold((x,y) => x-y)
<console>:19: error: missing parameter type
       l2.fold((x,y) => x-y)
                ^
<console>:19: error: missing parameter type
       l2.fold((x,y) => x-y)
                  ^
<console>:19: error: missing argument list for method fold in trait TraversableOnce
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `fold _` or `fold(_)(_)` instead of `fold`.
       l2.fold((x,y) => x-y)
              ^

scala> l2.fold(2)((x,y) => x-y)
res68: Int = -6

scala> l2.fold(2)(_+_)
res69: Int = 10

scala> l2.foldLeft(2)(_+_)
res70: Int = 10

scala> l2.foldRight(2)(_+_)
res71: Int = 10

scala> l2
res72: List[Int] = List(1, 3, 4)

scala> l2.fold(0)(_ - _)
res73: Int = -8

scala> l2.foldRight(0)(_ - _)
res74: Int = 2

scala> l2.foldLeft(0)(_ - _)
res75: Int = -8

scala> l2
res76: List[Int] = List(1, 3, 4)

scala> l2.reduce(_+_)
res77: Int = 8

scala> l2.reduce(_-_)
res78: Int = -6

scala> l2
res79: List[Int] = List(1, 3, 4)

scala> l2.aggregate(0)(_+_,_+_)
res80: Int = 8

scala> val l3 = List(6,7,8)
l3: List[Int] = List(6, 7, 8)

scala> l2.zip(l3)
res81: List[(Int, Int)] = List((1,6), (3,7), (4,8))

scala> val l3 = List(6,7,8,9)
l3: List[Int] = List(6, 7, 8, 9)

scala> l2.zip(l3)
res82: List[(Int, Int)] = List((1,6), (3,7), (4,8))

scala> l2
res83: List[Int] = List(1, 3, 4)

scala> l2.sum
res84: Int = 8

其中

scala> l2
res73: List[Int] = List(1, 3, 4)

//相当于 1-(3-(4-0)   右折叠初始值在右
scala> l2.foldRight(0)(_ - _)
res74: Int = 2

//相当于 (0-1)-3)-4)
scala> l2.foldLeft(0)(_ - _)
res75: Int = -8

六、Set

    无序的,不重复的集合
    Set不可变的集合
    val l5 = collection.mutable.HashSet(2,3,4)
    HashSet可变的集合
    remove 删除元素
    -= 删除元素
    ++ 集合相加
    ++= 相加并赋值

例:

scala> val l4 = List(1,2,2,4)
l4: List[Int] = List(1, 2, 2, 4)

scala> val s = Set(2,3,4)
s: scala.collection.immutable.Set[Int] = Set(2, 3, 4)

scala> val s = Set(2,3,3,4)
s: scala.collection.immutable.Set[Int] = Set(2, 3, 4)

scala> s += 5
<console>:19: error: value += is not a member of scala.collection.immutable.Set[Int]
       s += 5
         ^

scala> collection.mutable.Hash
HashEntry   HashMap   HashSet

scala> val l5 = collection.mutable.HashSet(2,3,4)
l5: scala.collection.mutable.HashSet[Int] = Set(2, 3, 4)

scala> l5 += 6
res86: l5.type = Set(2, 6, 3, 4)

scala> l5
res87: scala.collection.mutable.HashSet[Int] = Set(2, 6, 3, 4)

scala> l5,remove(2)
<console>:1: error: ‘;‘ expected but ‘,‘ found.
l5,remove(2)
  ^

scala> l5.remove(2)
res88: Boolean = true

scala> l5
res89: scala.collection.mutable.HashSet[Int] = Set(6, 3, 4)

scala> l5 -= 3
res90: l5.type = Set(6, 4)

scala> l4
res91: List[Int] = List(1, 2, 2, 4)

scala> l5
res92: scala.collection.mutable.HashSet[Int] = Set(6, 4)

scala> l4 ++ l5
res93: List[Int] = List(1, 2, 2, 4, 6, 4)

scala> l5 ++= Set(2,7)
res94: l5.type = Set(2, 6, 7, 4)

七、Map

    不可变Map:val m = Map[String,Int]("hello"->2,"world"->8)
    可变Map:
    getOrElse:如果有值返回值,没有返回默认值

例:

scala> val m = Map[String,Int]("hello"->2,"Beijing"->8)
m: scala.collection.immutable.Map[String,Int] = Map(hello -> 2, Beijing -> 8)

scala> m("hello")
res95: Int = 2

scala> m("hello") = 4
<console>:19: error: value update is not a member of scala.collection.immutable.Map[String,Int]
       m("hello") = 4
       ^

scala> val m2 = collection.mutable.HashMap[String,Int]()
m2: scala.collection.mutable.HashMap[String,Int] = Map()

scala> m2.put("lisi",18)
res97: Option[Int] = None

scala> m2
res98: scala.collection.mutable.HashMap[String,Int] = Map(lisi -> 18)

scala> m2 += "weight" -> 120
res99: m2.type = Map(lisi -> 18, weight -> 120)

scala> m2.remove("lisi")
res100: Option[Int] = Some(18)

scala> m2
res101: scala.collection.mutable.HashMap[String,Int] = Map(weight -> 120)

scala> m2 -= "weight"
res102: m2.type = Map()

scala> m2
res103: scala.collection.mutable.HashMap[String,Int] = Map()

scala> m2 += "weight" -> 120
res104: m2.type = Map(weight -> 120)

scala> m2.get("weight")
res105: Option[Int] = Some(120)

scala> m2.getOrElse("zhangsan",18)
res106: Int = 18

scala> m2
res107: scala.collection.mutable.HashMap[String,Int] = Map(weight -> 120)

scala> m2 += "zhangsan" -> 28
res108: m2.type = Map(zhangsan -> 28, weight -> 120)

scala> m2.getOrElse("zhangsan",18)
res109: Int = 28

八、元组tuple

    元组中可以是任意元素
    val t = (2,true,"lisi",Unit)
    取元素:t._1
    对偶元组:有两个元素的元组

例:

scala> val t = (2,true,"lisi",Unit)
t: (Int, Boolean, String, Unit.type) = (2,true,lisi,object scala.Unit)

scala> t
res110: (Int, Boolean, String, Unit.type) = (2,true,lisi,object scala.Unit)

scala> t._1
res111: Int = 2

scala> t._3
res112: String = lisi

scala> val t1 = ("lisi",18)
t1: (String, Int) = (lisi,18)

scala> t1.swap
res113: (Int, String) = (18,lisi)

scala> val t3 = Array(("lisi",18),("zhangsan",16))
t3: Array[(String, Int)] = Array((lisi,18), (zhangsan,16))

//求t3中的年龄的和
scala> t3.foldLeft(0)(_+_._2)
res114: Int = 34

原文地址:https://www.cnblogs.com/areyouready/p/10217512.html

时间: 2024-11-10 18:05:34

Scala数组和集合的相关文章

Scala学习笔记一之基础语法,条件控制,循环控制,函数,数组,集合

前言:Scala的安装教程:http://www.cnblogs.com/biehongli/p/8065679.html 1:Scala之基础语法学习笔记: 1:声明val变量:可以使用val来声明变量,用来存放表达式的计算结果,但是常量声明后是无法改变它的值的,建议使用val来声明常量: 声明var变量:如果要声明可以改变的引用,可以使用var变量,声明的常量的值可以改变. 3:指定类型:无论声明val变量还是声明var变量.都可以手动指定其类型,如果不指定,scala会自动根据值,进行类型

scala 数组转换

for(...)yield循环创建了一个类型与原始集合相同的新集合.  val a1 = Array(2, 3, 5, 7, 11)     val result = for (elem <- a1) yield 2 * elem     for (elem <- result) {       println(elem)     } 结果 4 6 10 14 22 通过守卫:for中的if 来实现处理那些满足特定条件的元素. val a1 = Array(2, 3, 5, 7, 11)   

Scala数组操作

数组要点 若长度固定则使用Array,若长度可能有变化则使用ArrayBuffer:提供初始值时不要使用new:用()来访问元素:用for(elem<-arr)来遍历元素:用for(elem<-arr if...)...yield...来将原数组转型为新数组:Scala数组和Java数组可以互操作,用ArrayBuffer,使用scala.collection.JavaConversions中的转换函数. 例子: import scala.collection.mutable.ArrayBuf

Scala 数组和List

Scala 数组和List: import scala.collection.mutable.ArrayBuffer import scala.collection.mutable.Buffer object ArrayLearning { def main (args: Array[String]): Unit = { // useZipUnzip // listOps // arrayOps // ArrayBufferOps } private def useZipUnzip = { //

4、scala数组

1.Array 2.ArrayBuffer 3.遍历Array和ArrayBuffer 4.数组常见操作 1.  Array Scala中,array代表的含义与java类似,也是长度不可改变的数组.由于scala与java都是运行在jvm中,双方可以相互调用,scala数组的底层实现实际上是java数组. 2.ArrayBuffer Scala中,如果需要长度可变的集合类,可以使用ArrayBuffer.使用前需要导入 scala.collection.mutable.ArrayBuffer.

C#语言中数组和集合

数组.集合→用于储存多个同类型的数据数组 定长→用于保存固定数量的数据 在功能上,数组能实现的所有功能,集合都能实现:反之,集合能实现的某些功能,数组难以实现 占用内存少 便利速度快集合 不定长→保存的数据数量,可以在程序的执行过程中,发生变化 占用内存多 便利速度慢课时六:数组和集合 数组.集合→用于储存多个同类型的数据 数组 定长→用于保存固定数量的数据 在功能上,数组能实现的所有功能,集合都能实现:反之,集合能实现的某些功能,数组难以实现 占用内存少 便利速度快 集合 不定长→保存的数据数

.NET 基础 一步步 一幕幕[数组、集合、异常捕获]

数组.集合.异常捕获 数组: 一次性存储多个相同类型的变量. 一维数组: 语法: 数组类型[] 数组名=new 数组类型[数组长度]; 声明数组的语法: A.数据类型 [] 数组名称= new 数据类型[2]{1,2}: B.数据类型 [] 数组名称 = new 数据类型[数组大小]; C. 数据类型 [] 数组名称 = {数据,数据,数据,数据}; ***数组的长度一旦固定了,就不能再被改变了 可以通过索引来访问数组中的元素: 数组名称[索引位置] 案例: 多维数组:多个线性数组的值 二维:i

非计算机专业的码农C#学习笔记 五、数组和集合

数组和集合 1.数组问题Array (1)一维数组:int[] arr={1,2,3,5,5} string[] s={s,l,s,g} (2)二维数组:int[,] arr=new int[2,2]{{1,2},{3,4}} 类型[,] 数组名=new 类型[行数(元素数),列数(元素的子元素数]{{元素1,元素2},{元素…},…,} l  动态数组:类型[,] 数组名=new 类型[M,N],int M=””;int N=””; l  查看内部元素:foreach(int n in arr

集合转数组,数组转集合,集合中只可以装引用数据类型

1 package com.pang.jihe_demo; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.List; 6 7 public class Demo01 { 8 public static void main(String[] args) { 9 //集合转数组,集合中只可以装引用数据类型 10 ArrayList<Integer> list = new ArrayList