(2 из 3)      << | < | 1 | 2 | 3 | > | >>

4. Arrays and Dictionaries

Arrays of fixed size:

val nums = new Array[Int](10) // size 10 of Int, init with 0
val ar = new Array[String](10) // size 10 of String, init with null
val s = Array("Hello","world") // Array[String], size 2
s(0) = "Bye" // change of first element

Arrays in Scala are translated to Java Arrays, for example Array(2, 11, 5, 3, 7) in JVM will be int[]. Arrays are Seq (scala List abstraction):

val a = Array(2, 11, 5, 3, 7) // Array of Int 
a(2) // 5
a.head // 2 
a.sorted // Array(2, 3, 5, 7, 11) 
a.reverse // Array(7, 3, 5, 11, 2)
a.sum  // Int = 28
a.filter(x => x%2==1).sum  // Int = 26
a.max  // Int = 11
a.map(x => x*x) // Array(4, 121, 25, 9, 49)

Transformation to String:

a.toString // [I@28f87cc
a.mkString(" and ")  // 2 and 11 and 5 and 3 and 7
a.mkString(",")  // 2,11,5,3,7
a.mkString("<", ",", ">")  // <2,11,5,3,7>

Variable length arrays:

import scala.collection.mutable.ArrayBuffer        
val b = ArrayBuffer[Int]() // or new ArrayBuffer[Int] - empty array of Int
b += 1 // ArrayBuffer(1)
b += (1,2,3,5) // ArrayBuffer(1,1,2,3,5)
b ++= Array(8, 13, 21) // ArrayBuffer(1, 1, 2, 3, 5, 8, 13, 21)
b.trimEnd(5) // ArrayBuffer(1, 1, 2) - remove 5 last elements
b.insert(2, 6) // ArrayBuffer(1, 1, 6, 2) - insert b(2)
b.insert(2, 7, 8, 9) // ArrayBuffer(1, 1, 7, 8, 9, 6, 2) - insert b(2),b(3),b(4)
b.remove(2) // ArrayBuffer(1, 1, 8, 9, 6, 2) - remove b(2)
b.remove(2,3) // ArrayBuffer(1, 1, 2) - remove b(2),b(3),b(4)
val c = b.toArray // Array(1, 1, 2)
c.toBuffer // ArrayBuffer(1, 1, 2)

Multi-dimensional arrays, for example Array[Array[Double]] is two-dimensional array of Double:

val matrix = Array.ofDim[Double](3, 4)  // 3 rows and 4 cols
matrix(2)(3)  // Double = 0.0
matrix(2)(3) = 42  
matrix(2)(3)  // Double = 42.0

Java to Scala collection conversion:

import scala.collection.JavaConversions._
val list = new java.util.ArrayList[String]()
list.add("abc")
list.toArray // Array(abc)
list.toBuffer // ArrayBuffer(abc)
val map = new java.util.HashMap[String, Int]
map.put("a", 10)
map.toMap // Map(a -> 10) - to Scala Map transformation

5. Collections: Lists, Sets, Maps and Streams

Immutable List is the main Seq trait implementation:

val l1 = List(1,2,3) // List of Int
l1(0) = 4 // Error - we can not change elements unlike arrays
val l2 = List() // List[Nothing]
l1 == Nil // false
l2 == Nil // true
val l3 = List(2,"a") // List[Any]
l3(1) // a
val l4 = List(1,-2,3,2,-1,0,-3)
l4.sorted // List(-3, -2, -1, 0, 1, 2, 3)
l4.sorted.reverse // List(3, 2, 1, 0, -1, -2, -3)
List("b","a").sorted // List(a, b)
List(1,"a").sorted // Error (Any do not have order)
l4.sortWith((x,y) => if (x*y>0) y x+"" < y+"") // List(1, a)

Mutable List - ListBuffer (like ArrayBuffer for Array):

import scala.collection.mutable.ListBuffer 
val lb = ListBuffer.empty[String]
lb += "a" // ListBuffer(a)
lb += ("c","d","e") // ListBuffer(a, c, d, e)
lb -= "d" // ListBuffer(a, c, e)
lb ++= List("f","g") // ListBuffer(a, c, e, f, g)

Set is implementation of Seq too, but there are differences with List:

List(1,1,2,2) // List(1,1,2,2)
Set(1,1,2,2) // Set(1,2)
List(1,2,3,4) ++ List(3,4,5,6) // List(1, 2, 3, 4, 3, 4, 5, 6)
Set(1,2,3,4) ++ Set(3,4,5,6) // Set(5, 1, 6, 2, 3, 4)
Set(1,2,3) == Set(3,1,2) // true
Set(1,2,3) + 2 // Set(1, 2, 3)
Set(1, 2, 3, 4, 5).toList // List(5, 1, 2, 3, 4)
Set(5, 4, 3, 2, 1).toList // List(5, 1, 2, 3, 4)

Immutable Map:

val scores0 = Map("John" -> 75, "Julia" -> 60, "Kevin" -> 26) // Map[String,Int] = Map(John -> 75, Julia -> 60, Kevin -> 26)
val scores1 = Map(("John", 75), ("Julia", 60), ("Kevin", 26)) // the same Map(John -> 75, Julia -> 60, Kevin -> 26)
scores0("Julia")  // Int = 60
if (scores0.contains("Julia")) scores0("Julia") else 0  // Int = 60
scores0.getOrElse("Julia",0)  // Int = 60 - the same as previous
scores0.get("Julia")  // Option[Int] = Some(60)
scores0.get("Jacob")  // Option[Int] = None
scores0.get("Julia").getOrElse(0)  // Int = 60
scores0.get("Jacob").getOrElse(0)  // Int = 0

Mutable Map:

import scala.collection.mutable.{Map => MMap}
val scores = MMap("John" -> 75, "Julia" -> 60, "Kevin" -> 26)
scores("Julia") = 55  // change of value
scores("Jacob") = 78  // adding of paar
scores += ("Julia" -> 55, "Jacob" -> 78)  // another way     
scores -= "Jacob"  // removing
val scores2 = scores + ("Julia" -> 55, "Jacob" -> 78) // new Map
val scores3 = scores - "Jacob" // new Map

Elements traversing:

for((k,v) <- scores) println((k,v))  // output: (key,value)
for((k,v) <- scores) println(k+" -> "+v)  // output: key -> value
scores.keySet  // keys to Set
for (v <- scores.values) println(v)  // only values
for((k,v) <- scores) yield (v,k)  // change places in paar (key value)

Streams are Lists with lazy access to elements:

val st = (1 to 100).toStream // Stream(1, ?) - only first element calculated
st.filter(_%10==0) // Stream(10, ?) - only first element calculated
st.filter(_%10==0).toList // List(10, 20, 30, 40, 50, 60, 70, 80, 90, 100) - all elements calculated

Endless Fibonacci numbers list:

val fibs: Stream[BigInt] = BigInt(1) #:: BigInt(1) #:: (fibs zip fibs.tail).map { n => n._1 + n._2 }
fibs.take(10).toList // List(1, 1, 2, 3, 5, 8, 13, 21, 34, 55)
fibs.slice(100,103).toList // List(573147844013817084101, 927372692193078999176, 1500520536206896083277)
(2 из 3)      << | < | 1 | 2 | 3 | > | >>

Комментарии (0)

Автор (*):Город:
Эл.почта:Сайт:
Текст (*):