Scala - Collections



what will be covered in this post include the following.
  • Sequence
  • Lists
  • Arrays
  • List Buffers (the builder of List) 
  • ArrayBuffers (the builder of Array)
  • Strings (via StringOps)
  • Sets and maps 

Lists 

Lists are such an element that you can provide fast insert and remove from the head of the list, comon operations of the list is as such .

// working with collections in Scala
//
// description: 
//  this is for working with collections, 
// what will be covered in this source file 
//   
//   Lists
//   Array
//   List Buffers
//   Strings (via StringOps)
//   Set and Maps
//     Default Sets and Maps
//     Sorted Sets and Maps
//   General Multable and immutable Collections.
//   Collection initialization
//   Conversions
//   Tuples


// -- List

val colors = List("red", "blue", "green")
colors.head
colors.tail
Next we will see the Arrays

Arrays

arrays that is a container that holds a sequence of elements and effeciently access an element at an arbitrary position. 

// -- Arrays
val fiveInts = new Array[Int](5)
val fiveToOne = Array(5, 4, 3, 2, 1)
fiveInts(0) = fiveToOne(4)

List buffers

list have fast quick access to the head of the list, but when you try to build a list, it is not going to be easy and you normally build the list backward by prepending elements to the front, then when you 're done,call reverse to get the element in the order you need. 

LIstBuffer, another alternative, A ListBuffer is a mutable object (scala.collection.mutable), which can help you build the list more effeciently. 
ListBuffer has constants time in prepending or appending. and it supports += for append, and +=: for prepend. 

// -- List Buffers
//   like a List builder, which is in the mutable namespace of the scala.collection NS
import scala.collection.mutable.ListBuffer

val buf = new ListBuffer[Int]
buf += 1
buf += 2

3 +=: buf  // add to the front
buf.toList

Array Buffer

An arrayBuffer is like an array, except that you can additionally add and remove elements from the beginning and end of the sequence. 

the namespace of the ArrayBuffer is located in the namespace of scala.collection.mutable.ArrayBuffer.

please see the following code example. 

// -- Array buffers
//   the Array's builder
import scala.collection.mutable.ArrayBuffer
val buf = new ArrayBuffer[Int]()
buf += 12
buf += 15
3 +=: buf
buf.length
buf(0)

string via StringOps

StringOps is like the StringBuilder that you have in C# or java, however, StringOps provides more..

the example code below shows that you can use methods exists. String class itself does not have the exist method, while the Scala compiler can convert the String class to StringOps, and it is the StringOps that allows you to use exist method. 

// -- Strings (via StringOps)
//   Predef has implicit conversion from String to StringOps, so you can use the 
//   following methods. 
def hasUpperCase(s : String) = s.exists(_.isUpper)
hasUpperCase("Robert Frost")
hasUpperCase("e e cummings")

Sets and maps 

next, we are going to discuss the set and maps,by default what you get from Scala set and maps are immutable sets and maps. 

the built-in set/maps are Predef ones.

// -- Sets and maps 
// a NOTE on the Sets and Maps, 
//   by default what you get for "Sets" and "Maps" are immutable ones, 
// which defined in the Predef object
// 
//object Predef { 
//  type Map[A, +B] = collection.immutable.Map[A, B]
//  type Set[A] = collection.immutable.Set[A]
//  val Map = collection.immutable.Map
//  val Set = collection.immutable.Set
//}
and if you try to use the mutable ones, as always, you have to import first the mutable packages.
// to use the mutable ones, use the following. 
import scala.collection.mutable
val mutaSet = mutable.Set(1, 2, 3)
an examples is like this
// -- using Sets
val text = "See SPot run, Run, Spot. Run!"
val wordsArray = text.split("[!,.]+")
val words = mutable.Set.empty[String]
for (word <- wordsArray) 
  words += word.toLowerCase
words
or you can use the map as following. 
// - using maps
def countWords(text : String) = { 
  val counts = mutable.Map.empty[String, Int]
  for (rawWord <- text.split("[!,.]+")) {
    val word = rawWord.toLowerCase
    val oldCount = 
      if (counts.contains(word)) counts(word)
      else 0
    counts += (word -> (oldCount + 1))
  }
  counts
}


countWords("See SPot run, Run, Spot. Run!")
and sometimes, we have to convert from those mutable ones to their immutable counterpart. 
and beside the run-off-the-mill/average Set/Map, Scala runtimne has offered several more Set and Maps. 
// - default Set and Maps
//   mutable sets and maps will returns a mutable.HashSet or a mutable.HashSet
// for immutable ones, 
//   1. immutable.EmptySet, 2. immutable.Set1, 3. immutable.Set2, 4. immutable.Set3 or 
//   1. immutable.EmptyMap, 2. immutable.Map1, 3. immutable.Map2, 4. immutable.Map3

Sorted set and Maps

Sorted set and Maps deserve their own section. . Normally the sorted varies are implemented as TreeSet or TreeMap, let's see some more examples. 

// -- Sorted Set and Maps 
//   TreeSet 
//   TreeMap
import scala.collection.immutable.TreeSet
val ts = TreeSet(9, 3, 1, 8, 0, 2, 7, 4, 6, 5)
ts // returns a sorted set 

import scala.collection.immutable.TreeMap
var tm = TreeMap(1 -> 'x', 3 -> 'x', 4 -> 'x')
tm += (2 -> 'x')

A note on Immutable Set and the Mutable set

while Immutable set and Mutable set all suports += operation, but hte semantic is quite difference, if you are doing += on immutable Set, a new Immutable set is returned, for Mutable set, the mutable set itself is updted. an examples. 
// -- immutable vs. mutables
val people = Set("Nancy", "Jane")
people += "Bob" // error, reassignment to the "people" which is a val value. 

// declare it to be var, so the varialbe itself can be updated, 
var people = Set("Nancy", "Jane")
people += "Bob" // while a new Immutable.Set(...) is returned 
  
  
people -= "Jane"
// you can append collection to a set 
people ++= List("Tom", "Harry")  

var capital = Map("US" -> "Washington", "France" -> "Paris")
capital += ("Japan" -> "Tokyo")
println(capital("France"))

// to use the immutable ones, do this
import scala.collection.mutable.Map
var capital = Map("US" -> "Washington", "France" -> "Paris")
capital += ("Japan" -> "Tokyo")
println(capital("France"))

Initializing collections

You can construct collections with the factory method. 

// -- Initializing Collections 
List(1, 2, 3)
Set('a', 'b', 'c')
val stuff = mutable.Set[Any](42)

val colors = List("Blue", "Yello", "Red", "Green")
// initialize a collection with anoter colleciton, you may use '++' operator
//val treeSet = TreeSet(colors) -- there is exceptions
val treeSet = TreeSet[String]() ++ colors

Conversion

to list or array.

// -- conversion
treeSet.toList
treeSet.toArray
conversion between mutable and immutable. 
// -- conversion between mutable and immutable
val mutaSet = mutable.Set.empty ++= treeSet
val immutaSet = Set.empty ++ mutaSet

val muta = mutable.Map("i" -> 1, "ii" -> 2)
val immuta = Map.empty ++ muta

Tuple

tuple is a light-weight, yet a very useful data structure, let's show an example of the Scala. 

// Tuples
def longestWord(words : Array[String]) = {
  var word = words(0)
  var idx = 0
  for (i <- 1 until words.length) { 
    if (words(i).length > word.length)
      word  = words(i)
      idx = i
  }

  (word, idx)
}
val longest = longestWord("The quick brown fox".split(" "))
longest._1
longest._2

转载于:https://my.oschina.net/u/854138/blog/134036

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值