SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Collections in Scala:
Advanced
Collections in Scala:
Advanced
Pranjut Gogoi & Bhavya Aggarwal
Knoldus Software LLP
Agenda
● Collection Hierarchy
● Traversable
● Iterable
● Seq
● Set
● Map
● Vector
● Stream
● ArrayBuffer
● Parallel Collections
Collection Hierarchy
Collection
Hierarchy
Agenda
● Collection Hierarchy
● Traversable
● Iterable
● Seq
● Set
● Map
● Vector
● Stream
● ArrayBuffer
● Parallel Collections
Traversable
● An iterator is traversing object which allows one to walk
through the collection.
● Trait Traversable conceptualize the concept of an internal
iterator
● Traversable only method is foreach
● A client code can be passed to the foreach method which will
be executed on each element of the collection it is being
applied
● foreach is side effective
Agenda
● Collection Hierarchy
● Traversable
● Iterable
● Seq
● Set
● Map
● Vector
● Stream
● ArrayBuffer
● Parallel Collections
Iterable
● Iterable is an external iterator.
● An external iterator is used to traverse a collection with
custom logic.
● The trait Iterable provides a methods iterator which is used
to get the iterator.
● Iterator can be used as an object to traverse through the
collection.
● Iterable provides methods used to traverse and access the
element from the collection without worrying about the
implementation of the collection.
Agenda
● Collection Hierarchy
● Traversable
● Iterable
● Seq
● Set
● Map
● Vector
● Stream
● ArrayBuffer
● Parallel Collections
Seq
● Represents collections that has a sequential ordering.
● Defined in terms of the length and apply method
● apply can be used to index into the collection while length is
used to calculate size of the collection
● Entertain as many duplicate elements as possible but in an
particular sequence
Linear Seq
● Sequence that can be partitioned in a head and a tail
component.
● The LinearSeq trait provides methods such as isEmpty,
head and tail.
● The examples of Linear Sequences are Lists, Stacks etc
● Linear Sequence are best suited for recursive algorithms
● All of the operations defined in the trait has constant time
complexity of element access O(1)
Indexed Seq
● Provides great ease in random access of elements in
Sequences
● It achieves constant or near constant time complexity while
accessing random elements from the sequence.
● The examples of an Indexed Seq is a Vector which behaves
like an array, providing near constant operations on a
immutable Object
val mySeq = IndexedSeq("A","B","C")
mySeq: IndexedSeq[String] = Vector(A, B, C)
Indexed Seq
● Provides great ease in random access of elements in
Sequences
● It achieves constant or near constant time complexity while
accessing random elements from the sequence.
● The examples of an Indexed Seq is a Vector which behaves
like an array, providing near constant operations on a
immutable Object
val mySeq = IndexedSeq("A","B","C")
mySeq: IndexedSeq[String] = Vector(A, B, C)
Agenda
● Collection Hierarchy
● Traversable
● Iterable
● Seq
● Set
● Map
● Vector
● Stream
● ArrayBuffer
● Parallel Collections
Set
● Trait that represents an unordered collection of unique
elements
● Provides methods like contains, subsetOf and apply
methods
● Best suited for requirements like checking the existence of
an element in a collection, Lookup Tables etc
● Scala provides three types of mutable and immutable Sets
implementations, TreeSet, HashSet and BitSet.
TreeSet
● Implemented as a red black tree of elements.
● A Red black tree is a self balancing binary search tree.
● Best suited for requirements like checking the existence of
an element in a collection, Lookup Tables etc
● It guarantees search operations in O(log n) time.
● A TreeSet construction required an implicit Ordering for
comparison of elements during storage.
HashSet
● Implemented as tree of elements but uses Hashing to place
elements in the tree.
● A hash value is calculated for each value and the values with
same hash values are kept at the same tree node.
● HashSet has constant time operations like insertion and
element retrieval from the tree.
● HashSet whose hash function has less chance of collision
can outperform TreeSet in lookup and search operations.
BitSet
● Implemented as sequence of Long Values.
● Can store only non-negative integer values
● Often used to store sequences of bits and memory flags
● The maximum memory consumed by the BitSet is
dependent upon the largest number stored in it.
● The base trait BitSet is implemented in both version in scala,
i.e. scala.collection.immutable.BitSet and
scala.collection.mutable.BitSet.
BitSet: Example
val bits = scala.collection.immutable.BitSet.empty //Initializing the empty BitSet
bits: scala.collection.immutable.BitSet = BitSet()
val addedBits = bits + 3 + 4 + 7 //Adding elements to the bit set
addedBits: scala.collection.immutable.BitSet = BitSet(3, 4, 7)
val finalBits = addedBits + 7 + 9 //Adding more elements
finalBits: scala.collection.immutable.BitSet = BitSet(3, 4, 7, 9)
Agenda
● Collection Hierarchy
● Traversable
● Iterable
● Seq
● Set
● Map
● Vector
● Stream
● ArrayBuffer
● Parallel Collections
Map
● The Map trait denotes collection of key value pairs
● Only one value for a given key exists
●
Scala provides two map implementation, i.e. HashMap and
TreeMap.
●
A HashMap is preferred when the hashing algorithm is
enhanced and have less chances of collision.
●
TreeMap and HashMap shares same performance trade-offs
that is in TreeSet and HashSet
Map: Example
val author = Map("Scala"->"Martin Ordersky","Java"->"E Bala","C"->"Dennis Ritchie")
author: scala.collection.immutable.Map[String,String]
val prices = Map("C"->100,"Java"->200,"Scala"->1000)
prices: scala.collection.immutable.Map[String,Int]
val priceOfCBook = prices.get("C")
priceOfCBook: Option[Int] = Some(100)
val priceOfDBook = prices.get("D")
priceOfDBook: Option[Int] = None
Agenda
● Collection Hierarchy
● Traversable
● Iterable
● Seq
● Set
● Map
● Vector
● Stream
● ArrayBuffer
● Parallel Collections
Vector
● Vector is an IndexedSeq
● It is very efficient in random accessing the elements
●
It has random access complexity of log32 (N)
●
Vectors are implemented as a trie on the index position of
the element.
●
A trie is a tree where each child down the path share some
common characteristics
Trie: Example
A trie with branching factor of two, where each element is stored
as its binary position in the tree.
A trie with branching factor of two, where each element is stored
as its binary position in the tree.
Vector:Example
● Vector is a good balance of properties like fast random
access and fast random updates
●
It is safe to share across thread since it is immutable:
val vector = Vector(1, 2, 3)
vector: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)
val updatedVector = vector updated (2, 4)
updatedVector: scala.collection.immutable.Vector[Int] = Vector(1, 2, 4)
vector
res0: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)
Agenda
● Collection Hierarchy
● Traversable
● Iterable
● Seq
● Set
● Map
● Vector
● Stream
● ArrayBuffer
● Parallel Collections
Stream
● Stream is a lazy persistent collection
●
It can store infinite sequences without overflowing the
memory constraints.
●
Streams are just like Lists and composed of cons nodes and
empty stream but
●
Stream is not evaluated until the elements are needed
●
It stores function objects instead of actual elements to
compute the head element and the rest of the stream
Stream:Example
val stream = Stream from 1
stream: scala.collection.immutable.Stream[Int] = Stream(1, ?)
stream.foreach(x => println(x))
1
2
3
..
35
Output exceeds cutoff limit.
val stream = Stream from 1
stream: scala.collection.immutable.Stream[Int] = Stream(1, ?)
stream.foreach(x => println(x))
1
2
3
..
35
Output exceeds cutoff limit.
Agenda
● Collection Hierarchy
● Traversable
● Iterable
● Seq
● Set
● Map
● Vector
● Stream
● ArrayBuffer
● Parallel Collections
ArrayBuffer
●
ArrayBuffer collection is a mutable Array defined in the
package scala.collection.mutable
●
Append, update and random access take constant time.
●
ArrayBuffer is created with some initial size given in the
constructor or with some default size defined.
●
When an element is added, the current size is checked,
●
if not sufficient a whole new array is allocated with a different
size and all previous element are moved into new array
along with new elements
ArrayBuffer
val arrayBuf:ArrayBuffer[Int] = new ArrayBuffer() //create empty array buffer
arrayBuf: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
arrayBuf.append(4) //append element 4 to it
arrayBuf.append(7,8) //append element 7 and 8 to it
arrayBuf // print the arrayBuf now , It will be updated in place
res3: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(4, 7, 8)
arrayBuf.size //Get the size of mutable array
res4: Int = 3 //It has grown to 4
Agenda
● Collection Hierarchy
● Traversable
● Iterable
● Seq
● Set
● Map
● Vector
● Stream
● ArrayBuffer
● Parallel Collections
Parallel Collections
●
Parallel collections in Scala aims to reduce the lower level
parallelism and programmer's level
●
It provides a high level abstraction of parallelism over normal
collections so they can be operated in parallel.
●
There are several wrapper methods available for normal
collection to get the parallel version.
●
One has to simply invoke the .par method on sequential
collections to operate it in parallel.
Parallel Collections
Example: Parallel Collections
References
● Scala In depth: by Joshua D. Suereth
● http://docs.scala-lang.org/overviews/collections/overview.html

Weitere ähnliche Inhalte

Was ist angesagt?

How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)Sangharsh agarwal
 
Standard template library
Standard template libraryStandard template library
Standard template librarySukriti Singh
 
Collections in Java
Collections in JavaCollections in Java
Collections in JavaKhasim Cise
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David SzakallasDatabricks
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL乐群 陈
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellDatabricks
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David SzakallasDatabricks
 
Standard template library
Standard template libraryStandard template library
Standard template libraryJancypriya M
 
java collections
java collectionsjava collections
java collectionsjaveed_mhd
 
Skillwise - Enhancing dotnet app
Skillwise - Enhancing dotnet appSkillwise - Enhancing dotnet app
Skillwise - Enhancing dotnet appSkillwise Group
 
Java collections
Java collectionsJava collections
Java collectionsAmar Kutwal
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google CollectionsAndré Faria Gomes
 
Intro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and ArrayIntro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and ArrayJeongbae Oh
 
Spark: Taming Big Data
Spark: Taming Big DataSpark: Taming Big Data
Spark: Taming Big DataLeonardo Gamas
 

Was ist angesagt? (20)

How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Distributed computing with spark
Distributed computing with sparkDistributed computing with spark
Distributed computing with spark
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David Szakallas
 
07 java collection
07 java collection07 java collection
07 java collection
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David Szakallas
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
java collections
java collectionsjava collections
java collections
 
Skillwise - Enhancing dotnet app
Skillwise - Enhancing dotnet appSkillwise - Enhancing dotnet app
Skillwise - Enhancing dotnet app
 
Java collections
Java collectionsJava collections
Java collections
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 
Lecture notesmap
Lecture notesmapLecture notesmap
Lecture notesmap
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
Intro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and ArrayIntro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and Array
 
STL in C++
STL in C++STL in C++
STL in C++
 
Spark: Taming Big Data
Spark: Taming Big DataSpark: Taming Big Data
Spark: Taming Big Data
 

Ähnlich wie Collection advance

Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collectionsKnoldus Inc.
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collectionsKnoldus Inc.
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On WorkshopArpit Poladia
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Sagar Verma
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_FrameworkKrishna Sujeer
 
Collections in java
Collections in javaCollections in java
Collections in javakejpretkopet
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Java collections
Java collectionsJava collections
Java collectionsSujit Kumar
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)Janki Shah
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdfssusere19c741
 

Ähnlich wie Collection advance (20)

Java Collections
Java  Collections Java  Collections
Java Collections
 
Scala collection
Scala collectionScala collection
Scala collection
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Java util
Java utilJava util
Java util
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
collections
collectionscollections
collections
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
 
Collections
CollectionsCollections
Collections
 
Collections in java
Collections in javaCollections in java
Collections in java
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java collections
Java collectionsJava collections
Java collections
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Collections in .net technology (2160711)
Collections in .net technology (2160711)Collections in .net technology (2160711)
Collections in .net technology (2160711)
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf
 

Kürzlich hochgeladen

定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一
 定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一 定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一
定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一Fs sss
 
Human Rights are notes and helping material
Human Rights are notes and helping materialHuman Rights are notes and helping material
Human Rights are notes and helping materialnadeemcollege26
 
LinkedIn Strategic Guidelines April 2024
LinkedIn Strategic Guidelines April 2024LinkedIn Strategic Guidelines April 2024
LinkedIn Strategic Guidelines April 2024Bruce Bennett
 
办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书saphesg8
 
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一z xss
 
Ioannis Tzachristas Self-Presentation for MBA.pdf
Ioannis Tzachristas Self-Presentation for MBA.pdfIoannis Tzachristas Self-Presentation for MBA.pdf
Ioannis Tzachristas Self-Presentation for MBA.pdfjtzach
 
Back on Track: Navigating the Return to Work after Parental Leave
Back on Track: Navigating the Return to Work after Parental LeaveBack on Track: Navigating the Return to Work after Parental Leave
Back on Track: Navigating the Return to Work after Parental LeaveMarharyta Nedzelska
 
定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一z zzz
 
办理(Salford毕业证书)索尔福德大学毕业证成绩单原版一比一
办理(Salford毕业证书)索尔福德大学毕业证成绩单原版一比一办理(Salford毕业证书)索尔福德大学毕业证成绩单原版一比一
办理(Salford毕业证书)索尔福德大学毕业证成绩单原版一比一diploma 1
 
LinkedIn for Your Job Search in April 2024
LinkedIn for Your Job Search in April 2024LinkedIn for Your Job Search in April 2024
LinkedIn for Your Job Search in April 2024Bruce Bennett
 
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一A SSS
 
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...nitagrag2
 
Black and White Minimalist Co Letter.pdf
Black and White Minimalist Co Letter.pdfBlack and White Minimalist Co Letter.pdf
Black and White Minimalist Co Letter.pdfpadillaangelina0023
 
美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作ss846v0c
 
Ch. 9- __Skin, hair and nail Assessment (1).pdf
Ch. 9- __Skin, hair and nail Assessment (1).pdfCh. 9- __Skin, hair and nail Assessment (1).pdf
Ch. 9- __Skin, hair and nail Assessment (1).pdfJamalYaseenJameelOde
 
Unlock Your Creative Potential: 7 Skills for Content Creator Evolution
Unlock Your Creative Potential: 7 Skills for Content Creator EvolutionUnlock Your Creative Potential: 7 Skills for Content Creator Evolution
Unlock Your Creative Potential: 7 Skills for Content Creator EvolutionRhazes Ghaisan
 
定制(UQ毕业证书)澳洲昆士兰大学毕业证成绩单原版一比一
定制(UQ毕业证书)澳洲昆士兰大学毕业证成绩单原版一比一定制(UQ毕业证书)澳洲昆士兰大学毕业证成绩单原版一比一
定制(UQ毕业证书)澳洲昆士兰大学毕业证成绩单原版一比一lvtagr7
 
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证diploma001
 
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一Fs
 

Kürzlich hochgeladen (20)

定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一
 定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一 定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一
定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一
 
Human Rights are notes and helping material
Human Rights are notes and helping materialHuman Rights are notes and helping material
Human Rights are notes and helping material
 
LinkedIn Strategic Guidelines April 2024
LinkedIn Strategic Guidelines April 2024LinkedIn Strategic Guidelines April 2024
LinkedIn Strategic Guidelines April 2024
 
办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书
 
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
 
Ioannis Tzachristas Self-Presentation for MBA.pdf
Ioannis Tzachristas Self-Presentation for MBA.pdfIoannis Tzachristas Self-Presentation for MBA.pdf
Ioannis Tzachristas Self-Presentation for MBA.pdf
 
Back on Track: Navigating the Return to Work after Parental Leave
Back on Track: Navigating the Return to Work after Parental LeaveBack on Track: Navigating the Return to Work after Parental Leave
Back on Track: Navigating the Return to Work after Parental Leave
 
Students with Oppositional Defiant Disorder
Students with Oppositional Defiant DisorderStudents with Oppositional Defiant Disorder
Students with Oppositional Defiant Disorder
 
定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一
 
办理(Salford毕业证书)索尔福德大学毕业证成绩单原版一比一
办理(Salford毕业证书)索尔福德大学毕业证成绩单原版一比一办理(Salford毕业证书)索尔福德大学毕业证成绩单原版一比一
办理(Salford毕业证书)索尔福德大学毕业证成绩单原版一比一
 
LinkedIn for Your Job Search in April 2024
LinkedIn for Your Job Search in April 2024LinkedIn for Your Job Search in April 2024
LinkedIn for Your Job Search in April 2024
 
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
 
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
 
Black and White Minimalist Co Letter.pdf
Black and White Minimalist Co Letter.pdfBlack and White Minimalist Co Letter.pdf
Black and White Minimalist Co Letter.pdf
 
美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作
 
Ch. 9- __Skin, hair and nail Assessment (1).pdf
Ch. 9- __Skin, hair and nail Assessment (1).pdfCh. 9- __Skin, hair and nail Assessment (1).pdf
Ch. 9- __Skin, hair and nail Assessment (1).pdf
 
Unlock Your Creative Potential: 7 Skills for Content Creator Evolution
Unlock Your Creative Potential: 7 Skills for Content Creator EvolutionUnlock Your Creative Potential: 7 Skills for Content Creator Evolution
Unlock Your Creative Potential: 7 Skills for Content Creator Evolution
 
定制(UQ毕业证书)澳洲昆士兰大学毕业证成绩单原版一比一
定制(UQ毕业证书)澳洲昆士兰大学毕业证成绩单原版一比一定制(UQ毕业证书)澳洲昆士兰大学毕业证成绩单原版一比一
定制(UQ毕业证书)澳洲昆士兰大学毕业证成绩单原版一比一
 
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
 
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
 

Collection advance

  • 1. Collections in Scala: Advanced Collections in Scala: Advanced Pranjut Gogoi & Bhavya Aggarwal Knoldus Software LLP
  • 2. Agenda ● Collection Hierarchy ● Traversable ● Iterable ● Seq ● Set ● Map ● Vector ● Stream ● ArrayBuffer ● Parallel Collections
  • 5. Agenda ● Collection Hierarchy ● Traversable ● Iterable ● Seq ● Set ● Map ● Vector ● Stream ● ArrayBuffer ● Parallel Collections
  • 6. Traversable ● An iterator is traversing object which allows one to walk through the collection. ● Trait Traversable conceptualize the concept of an internal iterator ● Traversable only method is foreach ● A client code can be passed to the foreach method which will be executed on each element of the collection it is being applied ● foreach is side effective
  • 7. Agenda ● Collection Hierarchy ● Traversable ● Iterable ● Seq ● Set ● Map ● Vector ● Stream ● ArrayBuffer ● Parallel Collections
  • 8. Iterable ● Iterable is an external iterator. ● An external iterator is used to traverse a collection with custom logic. ● The trait Iterable provides a methods iterator which is used to get the iterator. ● Iterator can be used as an object to traverse through the collection. ● Iterable provides methods used to traverse and access the element from the collection without worrying about the implementation of the collection.
  • 9. Agenda ● Collection Hierarchy ● Traversable ● Iterable ● Seq ● Set ● Map ● Vector ● Stream ● ArrayBuffer ● Parallel Collections
  • 10. Seq ● Represents collections that has a sequential ordering. ● Defined in terms of the length and apply method ● apply can be used to index into the collection while length is used to calculate size of the collection ● Entertain as many duplicate elements as possible but in an particular sequence
  • 11. Linear Seq ● Sequence that can be partitioned in a head and a tail component. ● The LinearSeq trait provides methods such as isEmpty, head and tail. ● The examples of Linear Sequences are Lists, Stacks etc ● Linear Sequence are best suited for recursive algorithms ● All of the operations defined in the trait has constant time complexity of element access O(1)
  • 12. Indexed Seq ● Provides great ease in random access of elements in Sequences ● It achieves constant or near constant time complexity while accessing random elements from the sequence. ● The examples of an Indexed Seq is a Vector which behaves like an array, providing near constant operations on a immutable Object val mySeq = IndexedSeq("A","B","C") mySeq: IndexedSeq[String] = Vector(A, B, C)
  • 13. Indexed Seq ● Provides great ease in random access of elements in Sequences ● It achieves constant or near constant time complexity while accessing random elements from the sequence. ● The examples of an Indexed Seq is a Vector which behaves like an array, providing near constant operations on a immutable Object val mySeq = IndexedSeq("A","B","C") mySeq: IndexedSeq[String] = Vector(A, B, C)
  • 14. Agenda ● Collection Hierarchy ● Traversable ● Iterable ● Seq ● Set ● Map ● Vector ● Stream ● ArrayBuffer ● Parallel Collections
  • 15. Set ● Trait that represents an unordered collection of unique elements ● Provides methods like contains, subsetOf and apply methods ● Best suited for requirements like checking the existence of an element in a collection, Lookup Tables etc ● Scala provides three types of mutable and immutable Sets implementations, TreeSet, HashSet and BitSet.
  • 16. TreeSet ● Implemented as a red black tree of elements. ● A Red black tree is a self balancing binary search tree. ● Best suited for requirements like checking the existence of an element in a collection, Lookup Tables etc ● It guarantees search operations in O(log n) time. ● A TreeSet construction required an implicit Ordering for comparison of elements during storage.
  • 17. HashSet ● Implemented as tree of elements but uses Hashing to place elements in the tree. ● A hash value is calculated for each value and the values with same hash values are kept at the same tree node. ● HashSet has constant time operations like insertion and element retrieval from the tree. ● HashSet whose hash function has less chance of collision can outperform TreeSet in lookup and search operations.
  • 18. BitSet ● Implemented as sequence of Long Values. ● Can store only non-negative integer values ● Often used to store sequences of bits and memory flags ● The maximum memory consumed by the BitSet is dependent upon the largest number stored in it. ● The base trait BitSet is implemented in both version in scala, i.e. scala.collection.immutable.BitSet and scala.collection.mutable.BitSet.
  • 19. BitSet: Example val bits = scala.collection.immutable.BitSet.empty //Initializing the empty BitSet bits: scala.collection.immutable.BitSet = BitSet() val addedBits = bits + 3 + 4 + 7 //Adding elements to the bit set addedBits: scala.collection.immutable.BitSet = BitSet(3, 4, 7) val finalBits = addedBits + 7 + 9 //Adding more elements finalBits: scala.collection.immutable.BitSet = BitSet(3, 4, 7, 9)
  • 20. Agenda ● Collection Hierarchy ● Traversable ● Iterable ● Seq ● Set ● Map ● Vector ● Stream ● ArrayBuffer ● Parallel Collections
  • 21. Map ● The Map trait denotes collection of key value pairs ● Only one value for a given key exists ● Scala provides two map implementation, i.e. HashMap and TreeMap. ● A HashMap is preferred when the hashing algorithm is enhanced and have less chances of collision. ● TreeMap and HashMap shares same performance trade-offs that is in TreeSet and HashSet
  • 22. Map: Example val author = Map("Scala"->"Martin Ordersky","Java"->"E Bala","C"->"Dennis Ritchie") author: scala.collection.immutable.Map[String,String] val prices = Map("C"->100,"Java"->200,"Scala"->1000) prices: scala.collection.immutable.Map[String,Int] val priceOfCBook = prices.get("C") priceOfCBook: Option[Int] = Some(100) val priceOfDBook = prices.get("D") priceOfDBook: Option[Int] = None
  • 23. Agenda ● Collection Hierarchy ● Traversable ● Iterable ● Seq ● Set ● Map ● Vector ● Stream ● ArrayBuffer ● Parallel Collections
  • 24. Vector ● Vector is an IndexedSeq ● It is very efficient in random accessing the elements ● It has random access complexity of log32 (N) ● Vectors are implemented as a trie on the index position of the element. ● A trie is a tree where each child down the path share some common characteristics
  • 25. Trie: Example A trie with branching factor of two, where each element is stored as its binary position in the tree. A trie with branching factor of two, where each element is stored as its binary position in the tree.
  • 26. Vector:Example ● Vector is a good balance of properties like fast random access and fast random updates ● It is safe to share across thread since it is immutable: val vector = Vector(1, 2, 3) vector: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3) val updatedVector = vector updated (2, 4) updatedVector: scala.collection.immutable.Vector[Int] = Vector(1, 2, 4) vector res0: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)
  • 27. Agenda ● Collection Hierarchy ● Traversable ● Iterable ● Seq ● Set ● Map ● Vector ● Stream ● ArrayBuffer ● Parallel Collections
  • 28. Stream ● Stream is a lazy persistent collection ● It can store infinite sequences without overflowing the memory constraints. ● Streams are just like Lists and composed of cons nodes and empty stream but ● Stream is not evaluated until the elements are needed ● It stores function objects instead of actual elements to compute the head element and the rest of the stream
  • 29. Stream:Example val stream = Stream from 1 stream: scala.collection.immutable.Stream[Int] = Stream(1, ?) stream.foreach(x => println(x)) 1 2 3 .. 35 Output exceeds cutoff limit. val stream = Stream from 1 stream: scala.collection.immutable.Stream[Int] = Stream(1, ?) stream.foreach(x => println(x)) 1 2 3 .. 35 Output exceeds cutoff limit.
  • 30. Agenda ● Collection Hierarchy ● Traversable ● Iterable ● Seq ● Set ● Map ● Vector ● Stream ● ArrayBuffer ● Parallel Collections
  • 31. ArrayBuffer ● ArrayBuffer collection is a mutable Array defined in the package scala.collection.mutable ● Append, update and random access take constant time. ● ArrayBuffer is created with some initial size given in the constructor or with some default size defined. ● When an element is added, the current size is checked, ● if not sufficient a whole new array is allocated with a different size and all previous element are moved into new array along with new elements
  • 32. ArrayBuffer val arrayBuf:ArrayBuffer[Int] = new ArrayBuffer() //create empty array buffer arrayBuf: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer() arrayBuf.append(4) //append element 4 to it arrayBuf.append(7,8) //append element 7 and 8 to it arrayBuf // print the arrayBuf now , It will be updated in place res3: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(4, 7, 8) arrayBuf.size //Get the size of mutable array res4: Int = 3 //It has grown to 4
  • 33. Agenda ● Collection Hierarchy ● Traversable ● Iterable ● Seq ● Set ● Map ● Vector ● Stream ● ArrayBuffer ● Parallel Collections
  • 34. Parallel Collections ● Parallel collections in Scala aims to reduce the lower level parallelism and programmer's level ● It provides a high level abstraction of parallelism over normal collections so they can be operated in parallel. ● There are several wrapper methods available for normal collection to get the parallel version. ● One has to simply invoke the .par method on sequential collections to operate it in parallel.
  • 37. References ● Scala In depth: by Joshua D. Suereth ● http://docs.scala-lang.org/overviews/collections/overview.html