Collections, Tuples and Maps
November 26, 2019 Leave a comment
Traverable: It is the root trait of all collections and offers very important methods
maps: maps, flatMap, collect
conversions: toArray, toList, toSeq
size info: isEmpty, size, nonEmpty
tests: exists, forAll
folds: foldLeft, foldRight, reduceLeft, reduceRight
retrieval: head, find, tail
string ops: mkString
By default we use immutable collections in scala
package object scala { type List[+A] = immutable.List[A] } object Predef { type Map[A, +B] = immutable.Map[A, B] type Set[A] = immutable.Set[A] } Note: By default Seq apply method returns list val aSeq = Seq(1, 3, 4, 2) // returns List println(aSeq(2)) // overloaded apply method to get value at this index = prints 3
Tuples
Tuple is an infinite ordered list. It has copy method similar to case classees.
val aTuple = new Tuple2[Int, String](2, "Hello Scala") // Tuples can be extended to 22 different parameters to be in consistent with functions // is same as val aTuple1 = Tuple2(2, "Hello Scala") val aTuple2 = (2, "Hello Scala") val aTuple3 = (2 -> "Hello Scala") println(aTuple._1) println(aTuple.copy(_2 = "Good Bye")) // copy methods similar to case classes println(aTuple.swap) // swaps key value positions
Maps
val phoneBook = Map(("Jim", 555), ("Niran" -> 999)).withDefaultValue("-1") println(phoneBook) println(phoneBook.contains("Niran")) println(phoneBook("Mary")) // throws error if key is not found // add new pairing val newPairing = ("Mary" -> 909) val newPhonebook = phoneBook + newPairing println(newPhonebook) // filterKeys println(phoneBook.filterKeys(_.startsWith("N"))) // mapValues println(phoneBook.mapValues(number => "01245-" + number)) // println(phoneBook.mapValues(number => number * 10)) // conversions to other collections println(phoneBook.toList) // list of tuples println(List(("Niran" -> 57687)).toMap) val names = List("Niran", "Naveen", "Jim", "John") println(names.groupBy(_.charAt(0)))
Recent Comments