Code Examples for

Programming in Scala, Fifth Edition

Return to chapter index

15 Working with Other Collections

Sample run of chapter's interpreter examples

15.1 Sequences


val colors = List("red", "blue", "green") colors.head // red colors.tail // List(blue, green)
val fiveInts = new Array[Int](5) // Array(0, 0, 0, 0, 0)
val fiveToOne = Array(5, 4, 3, 2, 1) // Array(5, 4, 3, 2, 1)
fiveInts(0) = fiveToOne(4) fiveInts // Array(1, 0, 0, 0, 0)
import scala.collection.mutable.ListBuffer val buf = new ListBuffer[Int] buf += 1 // ListBuffer(1) buf += 2 // ListBuffer(1, 2) 3 +=: buf // ListBuffer(3, 1, 2) buf.toList // List(3, 1, 2)
import scala.collection.mutable.ArrayBuffer
val buf = new ArrayBuffer[Int]()
buf += 12 // ArrayBuffer(12) buf += 15 // ArrayBuffer(12, 15)
buf.length // 2 buf(0) // 12
def hasUpperCase(s: String) = s.exists(_.isUpper) hasUpperCase("Robert Frost") // true hasUpperCase("e e cummings") // false

15.2 Sets and maps


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 // ... end Predef
import scala.collection.mutable
val mutaSet = mutable.Set(1, 2, 3)
val text = "See Spot run. Run, Spot. Run!" val wordsArray = text.split("[ !,.]+") // Array(See, Spot, run, Run, Spot, Run)
val words = mutable.Set.empty[String]
for word <- wordsArray do words += word.toLowerCase words // Set(see, run, spot)
val map = mutable.Map.empty[String, Int]
val map = mutable.Map.empty[String, Int]
map("hello") = 1 map("there") = 2 map // Map(hello -> 1, there -> 2)
map("hello") // 1
def countWords(text: String) = val counts = mutable.Map.empty[String, Int] for rawWord <- text.split("[ ,!.]+") do val word = rawWord.toLowerCase val oldCount = if counts.contains(word) then counts(word) else 0 counts += (word -> (oldCount + 1)) counts countWords("See Spot run! Run, Spot. Run!") // Map(spot -> 2, see -> 1, run -> 3)
import scala.collection.immutable.TreeSet val ts = TreeSet(9, 3, 1, 8, 0, 2, 7, 4, 6, 5) // TreeSet(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) val cs = TreeSet('f', 'u', 'n') // TreeSet(f, n, u)
import scala.collection.immutable.TreeMap var tm = TreeMap(3 -> 'x', 1 -> 'x', 4 -> 'x') // TreeMap(1 -> x, 3 -> x, 4 -> x) tm += (2 -> 'x') tm // TreeMap(1 -> x, 2 -> x, 3 -> x, 4 -> x)

15.3 Selecting mutable versus immutable collections


scala> val people = Set("Nancy", "Jane") val people: Set[String] = Set(Nancy, Jane) scala> people += "Bob" 1 |people += "Bob" |^^^^^^^^^ |value += is not a member of Set[String]
var people = Set("Nancy", "Jane") people += "Bob" people // Set(Nancy, Jane, Bob)
people -= "Jane" people ++= List("Tom", "Harry") people // Set(Nancy, Bob, Tom, Harry)
// In file working-with-other-collections/Capitals.scala var capital = Map("US" -> "Washington", "France" -> "Paris") capital += ("Japan" -> "Tokyo") println(capital("France"))
// In file working-with-other-collections/Capitals.scala import scala.collection.mutable.Map // only change needed! var capital = Map("US" -> "Washington", "France" -> "Paris") capital += ("Japan" -> "Tokyo") println(capital("France"))
var roughlyPi = 3.0 roughlyPi += 0.1 roughlyPi += 0.04 roughlyPi // 3.14

15.4 Initializing collections


List(1, 2, 3) Set('a', 'b', 'c') import scala.collection.mutable mutable.Map("hi" -> 2, "there" -> 5) Array(1.0, 2.0, 3.0)
scala> import scala.collection.mutable scala> val stuff = mutable.Set(42) val stuff: scala.collection.mutable.Set[Int] = HashSet(42) scala> stuff += "abracadabra" 1 |stuff += "abracadabra" | ^^^^^^^^^^^^^ | Found: ("abracadabra" : String) | Required: Int
scala> val stuff = mutable.Set[Any](42) val stuff: scala.collection.mutable.Set[Any] = HashSet(42)
val colors = List("blue", "yellow", "red", "green")
scala> import scala.collection.immutable.TreeSet scala> val treeSet = TreeSet(colors) 1 |val treeSet = TreeSet(colors) | ^ |No implicit Ordering defined for List[String]..
val treeSet = colors to TreeSet // TreeSet(blue, green, red, yellow)
treeSet.toList // List(blue, green, red, yellow)
treeSet.toArray // Array(blue, green, red, yellow)
import scala.collection.mutable treeSet // TreeSet(blue, green, red, yellow) val mutaSet = treeSet to mutable.Set // mutable.HashSet(red, blue, green, yellow) val immutaSet = mutaSet to Set // // Set(red, blue, green, yellow)
val muta = mutable.Map("i" -> 1, "ii" -> 2) muta // mutable.HashMap(i -> 1, ii -> 2) val immu = muta to Map // Map(ii -> 2, i -> 1)

15.5 Tuples


// In file working-with-other-collections/Misc.scala (1, "hello", Console)
def longestWord(words: Array[String]): (String, Int) = var word = words(0) var idx = 0 for i <- 1 until words.length do if words(i).length > word.length then word = words(i) idx = i (word, idx)
val longest = longestWord("The quick brown fox".split(" ")) // (quick,1)
scala> longest(0) val res0: String = quick scala> longest(1) val res1: Int = 1
scala> val (word, idx) = longest val word: String = quick val idx: Int = 1 scala> word val res55: String = quick
scala> val word, idx = longest val word: (String, Int) = (quick,1) val idx: (String, Int) = (quick,1)

15.6 Conclusion

For more information about Programming in Scala, Fifth Edition (the "Stairway Book"), please visit:

http://www.artima.com/shop/programming_in_scala_5ed

and:

http://booksites.artima.com/programming_in_scala_5ed

Copyright © 2007-2020 Artima, Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.