Collections
- collection framework provides data structures for collecting one or more values of given types
collection class hierarchy
Iterable-> traitCollection->traitSeq-> traitList-> sealed abstractArray-> finalArray Buffer
Set-> traitSet-> immutableSet-> mutable
Map-> traitMap-> immutablesMap-> mutable
array
- contiguous memory allocated
- elements can be accesses using indices
- homogeneous elements
val numbers = new Array[Int](5)
numbers: Array[Int] = Array(0,0,0,0,0)
arr.toListconvert array to listarr.toStringconvert array to string
array buffer
- dynamic memory allocation
- no need to specify the size
// no need to specify the size
val buf = new ArrayBuffer[Int]()
// use some initial size
val buf = new ArrayBuffer[Int](10)
buf += 12buf += 15
lists
- like arrays but
- immutable
- have recursive structure, where array don't
- homogeneous elements
With type inference:
var fruit = List("apple", "banana", "pear")
var nums = List(1,2,3,4,5)
var listinlist = List(List(1,2,3), List(1,2,4), List(3,4,5))
var emptyList = List()
Without type inference:
var fruit:List[String] = List("apple", "banana", "pear")
var nums:List[Int] = List(1,2,3,4,5)
var listinlist:List[List[Int]] = List(List(1,2,3), List(1,2,4), List(3,4,5))
var emptyList:List[Nothing] = List()
- list types are covariant
- that means
- if
Sis subtype ofTthen List[S]is subtype ofList[T]- e.g.
List[String]is subtype ofList[Object]
- list is build form two fundamental building blocks
Niland::(cons) Nilrepresent empty list::(infix operator) expresses list extension ar the frontx::xs- represents list with first elementxfollowed by listxs
val fruits = "apple" :: ("oranges" :: ("bananan" :: Nil))
basic operations on the list
l.headreturns the first element of the listl.tailreturns a list with the first element removedl.isEmptyreturntrueif list has no elements otherwisefalsel.lengthreturn the length of the listl.last- return the end elementl.init- return a list removing the last elementl.reverse- reverse the listl.toArray- convert list to arrayl.toString- convert list to a stringl.copyTo(arr, startidx)- copy the list toarrstarting fromstartidxof arrayl.take(n)- return a list of firstnelementsl.drop(n)- return a list of elements except firstnelementsl.splitAt(n)- return two list split atn
l(n)returnnelement- l.apply(n)
returnn` element l.indicesreturn a list of the indices given in listl.mkString(prefix, separator, suffix)- set prefix, separator, and suffix while converting to string
var l = List('a', 'b', 'c', 'd', 'e')
println(l.mkString("[", ",", "]") // [a,b,c,d,e]
println(l.mkString("List(", ",", "]") // List(a,b,c,d,e]
concatenating lists
val a = List(1,2) ::: List(3,4,5)
// or
val a = List.concat(List(1,2), List(3,4,5))
pattern matching in list
- simple pattern matching
val fruit = List("apple", "mango", "banana")
val List(a,b,c) = fruit
// a = "apple"
// b = "mango"
// c = "banana"
- when list size is unknown
val fruit = List("apple", "mango", "banana", "pear", "onion")
var a :: b :: rest = fruit
// a = "apple"
// b = "mango"
// c = List("banana", "pear", "onion")
higher order function in list
filter
l- a list of typeTfun- a predicate function of typeT=>Booleanl.filter(fun)return a list of elements for whichfunreturntrue
var a = List(1,2,3,4,5)
var b = a.filter(_ % 2 == 0) // b = List(2,4)
partition
l- a list of typeTfun- a predicate function of typeT=>Booleanl.partition(fun)- return a tuple of list
- of elements for which
funreturntrue - and of elements for which
funreturnfalse
find
l- a list of typeTfun- a predicate function of typeT=>Booleanl.find(fun)-- return first element satisfying a given predicate
- return
Noneif no element is found
takeWhile
l- a list of typeTfun- a predicate function of typeT=>Booleanl.takeWhile(fun)- take values tillfunreturntrue
dropWhile
l- a list of typeTfun- a predicate function of typeT=>Booleanl.takeWhile(fun)- drop values tillfunreturntrue
span
l- a list of typeTfun- a predicate function of typeT=>Booleanl.span(fun)- return a tuple
(l.takeWhile(fun), l.dropWhile(fun))
- return a tuple
map
- apply a function to whole list and return it
val add10: Int => Int = _ + 10 // A function taking an Int and returning an Int
List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element
foreach
l- a list of typeTfun- a predicate function of typeT=>Unitl.foreach(fun)- runfunfor every value in the list
e.g.
val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
aListOfNumbers foreach (x => println(x))
aListOfNumbers foreach println
tuples
e.g.
(1, 2)(4, 3, 2)(1, 2, "three")(a, 2, "three")val divideInts = (x: Int, y: Int) => (x / y, x % y)- function returning a tuple
_._n - access n element of the tuple, 1 based index
val d = divideInts(10, 3) // (Int, Int) = (3,1)
d._1 // Int = 3
d._2 // Int = 1
also use multiple variable assignment
val (div, mod) = divideInts(10, 3)
div // Int = 3
mod // Int = 1
option
- Scala
Option[T]is a container for zero or one element of a given type. - An
Option[T]can be eitherSome[T]orNoneobject, which represents a missing value.
ranges
x to y by z=x until (y+1) by zval range = 0 until 10giveRange(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)- start = 0
- end = 9 // not 10 but 9
- step = 1
(0 to 10) by 5givesRange(0, 5, 10),- start = 0
- end = 10
- step = 5
byis used to set the step size
set
- unordered elements, implements using hashing
- cannot retrieve nth element as it is unordered
~
val colors = Set("red", "green", "blue")- adding new elements -
colors + "yellow" - removing elements -
colors - "green" - union elements -
colors ++ Set("black", "white") - difference of set -
colors -- Set("red", "green")
~
s.heads.tails.isEmptys.mins.maxs.intersect(s2)s.contains(ele)
maps
- like look up tables
- stored as key, value
val ordinals = Map(0 -> "zero", 1 -> "one", 2 -> "two")- access element
ordinals(2)gives"two"
~
s.keysreturn iterable containing keyss.valuesreturn iterable containing valuess.isEmptys.get(key)get value associated with keys.contains(key)check if key is present