scala总结(2)-- 集合类型

pattern matching 生成list 或是vector等的技巧:

case class: a class that can use cases pattern

e match {
  case p1 => exp1
  case p2 => exp2
...
}
a match exception will be thrown if no match were found

p1 .. pn these patterns:
use constructor to make sure the class, like Num(n)  then you can use n, or Num(_), _ means everything. or Num(1)

--

for () yield will generate a collection, like Vector
someList.map(someMethod) will do the same

if the method generate some collections, like List, then map will generate List(List). To fully use List, use flatMap. e.g.: 

val names = List(“Peter”, “Paul")
def foo(s:String) = Vectot(s.toUpperCase(), s.toLowerCase())

names.map(foo)   generate List(Vector(“PETER”, “peter”), Vector(“PAUL”, “paul"))
name.flatMap(foo) generate List(“PETER”, “peter”, “PAUL”, “paul")


其他集合类型的基本用法:
List in Scala:

val test = List(1,2,3)
val test2 = List(List(0,1,2), List(1,2,3), List(2,3,4))


Vector in Scala

val test = Vector(1,2,3)

near to random access, support all vector operations except :: is replaced by +: or :+ where : will point to sequences like x +: xs

Pair in Scala:
val pair = (“answer”, 42)  
//get pair content
val (a, b) = pair
//a = “string” b = 42

can be expanded to n-tuple

Map in Scala:
     iterating pairs in map:    
          for ((k, v) <- map ) process k and v
     iterating keys:
           scores.keySet // A set such as Set("Bob", "Cindy", "Fred", "Alice")
     iterating values:
           for (v <- scores.values) println(v)
==>
Tuple in Scala:      
     val t = (1, 3.14, "Fred")
     val second = t._2 // Sets second to 3.14, start indexing at 1!
    generating Tuple from Array:  
          val symbols = Array("<", "-", ">")
          val counts = Array(2, 10, 2)
          val pairs = symbols.zip(counts)
          //yields:
          Array(("<", 2), ("-", 10), (">", 2))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值