Upcoming SlideShare
×

# Scala collections

7,260

Published on

Published in: Technology
2 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total Views
7,260
On Slideshare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
71
0
Likes
2
Embeds 0
No embeds

No notes for slide

### Scala collections

1. 1. Scala CollectionsiBAT Session > June 17 2011 > Meetu Maltiar
2. 2. An Examplepackage com.inphina.collections.personclass Person(val name: String, val age: Int) { }Somewhere in the code:val (minors, adults) = people partition (_.age < 18)Three concepts: - Simple pattern matching - An Infix method call - A function value
3. 3. The Scala Way Of Collectionsscala> val ys = List(1, 2, 3)ys: List[Int] = List(1, 2, 3)scala> val xs: Seq[Int] = ysxs: Seq[Int] = List(1, 2, 3)scala> xs map (_ + 1)res0: Seq[Int] = List(2, 3, 4)scala> ys map (_ + 1)res1: List[Int] = List(2, 3, 4)
4. 4. Collection PropertiesObject-orientedGeneric: List[T], Map[K, V]optionally persistent: scala.collections.immutableHigher-order with methods like foreach, map, filteruniform return type principle: operations returncollections of same type as their left operand
5. 5. The Uniform Return Type PrincipleBulk operations return collections of the same type (constructor) astheir left operand.scala> val ys = List(1,2,3)ys: List[Int] = List(1, 2, 3)scala> val xs: Seq[Int] = ysxs: Seq[Int] = List(1, 2, 3)scala> xs map(_ + 1)res0: Seq[Int] = List(2, 3, 4)scala> ys map(_ + 1)res1: List[Int] = List(2, 3, 4)
6. 6. Using Collections: Map and Filterscala> val xs = List(1, 2, 3)xs: List[Int] = List(1, 2, 3)scala> val ys = xs map (x => x + 1)ys: List[Int] = List(2, 3, 4)scala> val ys = xs map (_ + 1)ys: List[Int] = List(2, 3, 4)scala> val zs = ys filter (_ % 2 == 0)zs: List[Int] = List(2 , 4)scala> val as = ys map (0 to _)as: List[scala.collection.immutable.Range.Inclusive] =List(Range(0, 1), Range(0, 1, 2), Range(0, 1, 2, 3))
7. 7. Using Collections: flatMap and groupByscala> val bs = as.flattenbs: List[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)scala> val bs = ys flatMap (0 to _)bs: List[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)scala> val fruit = Vector("apples", "oranges", "ananas")fruit: scala.collection.immutable.Vector[java.lang.String] =Vector(apples, oranges, ananas)scala> fruit groupBy (_.head)res3:scala.collection.immutable.Map[Char,scala.collection.immutable.Vector[java.lang.String]] = Map(a -> Vector(apples, ananas), o ->Vector(oranges))
8. 8. Using Collections: For Notationscala> for (x <- xs) yield x + 1 // mapres7: Seq[Int] = List(2, 3, 4)scala> for (x <- res7 if x % 2 == 0 ) yield x // filterres8: Seq[Int] = List(2, 4)scala> for (x <- xs; y <- 0 to x) yield y // flatMapres9: Seq[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)
9. 9. String also a CollectionEven String is also a collection that means we canapply higher order functions on it.scala> val aString = "hello world"aString: java.lang.String = hello worldscala> aString map (_.toUpper)res12: String = HELLO WORLD
10. 10. Using Mapsscala> val m = Map(1 -> "ABC", 2 -> "DEF", 3 -> "GHI")m: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -> ABC,2 -> DEF, 3 -> GHI)scala> m(2)res10: java.lang.String = DEFscala> m + (4 -> "JKL")res11: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 ->ABC, 2 -> DEF, 3 -> GHI, 4 -> JKL)scala> m map {case (k, v) => (v, k)}res12: scala.collection.immutable.Map[java.lang.String,Int] = Map(ABC-> 1, DEF -> 2, GHI -> 3)
11. 11. Scala Collection HierarchyAll Collection classes are in scala.collection or one of its sub-packages mutable, immutable and genericRoot collections in the package scala.collection define thesame interface as immutable collections and mutablecollections add some modification operations to make itmutableThe generic package contains building block for implementingCollections.
12. 12. Scala.Collection Hierarchy
13. 13. Scala.Collection.Immutable
14. 14. Scala.Collection.Mutable
15. 15. Overview Of CollectionsTraversable Iterable Seq IndexedSeq LinearSeq mutable.Buffer Range Set SortedSet immutable.HashSet mutable.HashSet mutable.LinkedHashSet BitSet Map SortedMap immutable.HashMap mutable.HashMap mutable.LinkedHashMap
16. 16. Commonality In collectionsAll classes are quite common. For instance, everykind of collection can be created by same uniformSyntax Traversable(1, 2, 3) Iterable("x", "y", "z") Map("x" -> 24, "y" -> 25, "z" -> 26) Set(Color.red, Color.green, Color.blue) SortedSet("hello", "world") Buffer(x, y, z) IndexedSeq(1.0, 2.0) LinearSeq(a, b, c)The same principle applies with specific collection implementations List(1, 2, 3) HashMap("x" -> 24, "y" -> 25, "z" -> 26)
17. 17. Commonality In collections...All these Collections get displayed with toString in the same waythey are written aboveAll collections support the API provided by Traversable butspecializes types wherever it makes sensemap method in class Traversable returns another Traversable asits result. But this result type is overridden in subclasses scala> List(1, 2, 3) map (_ + 1) res0: List[Int] = List(2, 3, 4) scala> Set(1, 2, 3) map (_ * 2) res0: Set[Int] = Set(2, 4, 6)This behavior in the collections libraries is called the uniform return type principle.
18. 18. Trait TraversableTop of collection hierarchy. Its abstract method is foreach:def foreach[U](f: Elem => U)Traversable also provides lot of concrete methods they fall infollowing categories Addition: ++, appends two traversables together Map operations: map, flatMap, and collect Conversions: toArray, toList, toIterable, toSeq, toIndexedSeq, toStream, toSet, toMap, Copying operations: copyToBuffer and copyToArray Size info operations: isEmpty, nonEmpty, size, and hasDefiniteSize Element retrieval operations: head, last, headOption, lastOption, and find Sub-Collection retrieval operations: tail, init, slice, take, drop, takeWhile, dropWhile, filter, filterNot, withFilter Subdivision operations: splitAt, span, partition, groupBy Element tests: exists, forall, count Folds: foldLeft, foldRight, /:, :, reduceLeft, reduceRight Specific Folds: sum, product, min, max String Operations: mkString, addString, stringPrefix
19. 19. Trait IterableThis is the next Trait in Collection hierarchy. All methods in this traitare defined in terms of an abstract method iterator, which returnscollection results one by one.The foreach method from trait Traversable is implemented inIterable in terms of iteratordef foreach[U](f: Elem => U): Unit = { val it = iterator while (it.hasNext) f(it.next())}
20. 20. An Example ..Task: Phone keys has mnemonics attached to themval mnemonics = Map( 2 -> "ABC", 3 -> "DEF", 4 -> "GHI", 5 -> "JKL", 6 -> "MNO", 7 -> "PQRS", 8 -> "TUV", 9 -> "WXYZ")Assume that you are given a dictionary dict as a list of words. Design aclass Coder with a method translate such that new Coder(dict).translate(phoneNumber)Produces all phrases of words which can serve as mnemonics for thephone numberExample The phone number “7225276257” should have a mnemonic Scala rocksas one element of the list of solution phrases
21. 21. An ExampleCreating a mnemonics Mapval mnemonics = Map(2 -> "ABC", 3 -> "DEF", 4 -> "GHI", 5 -> "JKL",6 -> "MNO", 7 -> "PQRS", 8 -> "TUV", 9 -> "WXYZ")Creating reverse map with upper codeval upperCode: Map[Char, Char] = for ((digit, str) <- mnemonics; ltr <- str)yield (ltr -> digit)Creating a word for which digit string will be generatedval word = "java"Gettng a digit string from a word eg; "java" -> "5282"word.toUpperCase map (upperCode(_))
22. 22. Everything is a libraryCollections feel they are language constructsLanguage does not contain any collection relatedconstructs - no collection types - no collection literals - no collection operatorsEverything is in libraryThey are extensible
23. 23. ConclusionDe-emphasize destructive updatesFocus on Transformers that map collections to collectionsHave complete range of persistent collections
24. 24. Next StepsMaking and extending Scala CollectionParallel Collections:Move from Mutable → Persistent → Parallel
25. 25. ReferencesMartin Oderskys talk at ParleysScala Collection documentation
1. #### A particular slide catching your eye?

Clipping is a handy way to collect important slides you want to go back to later.