SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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
 

What's hot (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
 

Similar to 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
 

Similar to 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
 

Recently uploaded

VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...Suhani Kapoor
 
Full Masii Russian Call Girls In Dwarka (Delhi) 9711199012 💋✔💕😘We are availab...
Full Masii Russian Call Girls In Dwarka (Delhi) 9711199012 💋✔💕😘We are availab...Full Masii Russian Call Girls In Dwarka (Delhi) 9711199012 💋✔💕😘We are availab...
Full Masii Russian Call Girls In Dwarka (Delhi) 9711199012 💋✔💕😘We are availab...shivangimorya083
 
Low Rate Call Girls Gorakhpur Anika 8250192130 Independent Escort Service Gor...
Low Rate Call Girls Gorakhpur Anika 8250192130 Independent Escort Service Gor...Low Rate Call Girls Gorakhpur Anika 8250192130 Independent Escort Service Gor...
Low Rate Call Girls Gorakhpur Anika 8250192130 Independent Escort Service Gor...Suhani Kapoor
 
PM Job Search Council Info Session - PMI Silver Spring Chapter
PM Job Search Council Info Session - PMI Silver Spring ChapterPM Job Search Council Info Session - PMI Silver Spring Chapter
PM Job Search Council Info Session - PMI Silver Spring ChapterHector Del Castillo, CPM, CPMM
 
VIP Call Girls Service Saharanpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Saharanpur Aishwarya 8250192130 Independent Escort Ser...VIP Call Girls Service Saharanpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Saharanpur Aishwarya 8250192130 Independent Escort Ser...Suhani Kapoor
 
Business Development and Product Strategy for a SME named SARL based in Leban...
Business Development and Product Strategy for a SME named SARL based in Leban...Business Development and Product Strategy for a SME named SARL based in Leban...
Business Development and Product Strategy for a SME named SARL based in Leban...Soham Mondal
 
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士obuhobo
 
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...shivangimorya083
 
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service CuttackVIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service CuttackSuhani Kapoor
 
Call Girls In Bhikaji Cama Place 24/7✡️9711147426✡️ Escorts Service
Call Girls In Bhikaji Cama Place 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Bhikaji Cama Place 24/7✡️9711147426✡️ Escorts Service
Call Girls In Bhikaji Cama Place 24/7✡️9711147426✡️ Escorts Servicejennyeacort
 
Production Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjProduction Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjLewisJB
 
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Employee of the Month - Samsung Semiconductor India Research
Employee of the Month - Samsung Semiconductor India ResearchEmployee of the Month - Samsung Semiconductor India Research
Employee of the Month - Samsung Semiconductor India ResearchSoham Mondal
 
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...Suhani Kapoor
 
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...shivangimorya083
 
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service BhilaiVIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service BhilaiSuhani Kapoor
 
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012rehmti665
 
The Impact of Socioeconomic Status on Education.pdf
The Impact of Socioeconomic Status on Education.pdfThe Impact of Socioeconomic Status on Education.pdf
The Impact of Socioeconomic Status on Education.pdftheknowledgereview1
 

Recently uploaded (20)

VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
 
Full Masii Russian Call Girls In Dwarka (Delhi) 9711199012 💋✔💕😘We are availab...
Full Masii Russian Call Girls In Dwarka (Delhi) 9711199012 💋✔💕😘We are availab...Full Masii Russian Call Girls In Dwarka (Delhi) 9711199012 💋✔💕😘We are availab...
Full Masii Russian Call Girls In Dwarka (Delhi) 9711199012 💋✔💕😘We are availab...
 
Low Rate Call Girls Gorakhpur Anika 8250192130 Independent Escort Service Gor...
Low Rate Call Girls Gorakhpur Anika 8250192130 Independent Escort Service Gor...Low Rate Call Girls Gorakhpur Anika 8250192130 Independent Escort Service Gor...
Low Rate Call Girls Gorakhpur Anika 8250192130 Independent Escort Service Gor...
 
PM Job Search Council Info Session - PMI Silver Spring Chapter
PM Job Search Council Info Session - PMI Silver Spring ChapterPM Job Search Council Info Session - PMI Silver Spring Chapter
PM Job Search Council Info Session - PMI Silver Spring Chapter
 
VIP Call Girls Service Saharanpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Saharanpur Aishwarya 8250192130 Independent Escort Ser...VIP Call Girls Service Saharanpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Saharanpur Aishwarya 8250192130 Independent Escort Ser...
 
Business Development and Product Strategy for a SME named SARL based in Leban...
Business Development and Product Strategy for a SME named SARL based in Leban...Business Development and Product Strategy for a SME named SARL based in Leban...
Business Development and Product Strategy for a SME named SARL based in Leban...
 
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
内布拉斯加大学林肯分校毕业证录取书( 退学 )学位证书硕士
 
Call Girls In Prashant Vihar꧁❤ 🔝 9953056974🔝❤꧂ Escort ServiCe
Call Girls In Prashant Vihar꧁❤ 🔝 9953056974🔝❤꧂ Escort ServiCeCall Girls In Prashant Vihar꧁❤ 🔝 9953056974🔝❤꧂ Escort ServiCe
Call Girls In Prashant Vihar꧁❤ 🔝 9953056974🔝❤꧂ Escort ServiCe
 
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
 
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service CuttackVIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
VIP Call Girls in Cuttack Aarohi 8250192130 Independent Escort Service Cuttack
 
Call Girls In Bhikaji Cama Place 24/7✡️9711147426✡️ Escorts Service
Call Girls In Bhikaji Cama Place 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Bhikaji Cama Place 24/7✡️9711147426✡️ Escorts Service
Call Girls In Bhikaji Cama Place 24/7✡️9711147426✡️ Escorts Service
 
Production Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjProduction Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbj
 
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Ex 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Employee of the Month - Samsung Semiconductor India Research
Employee of the Month - Samsung Semiconductor India ResearchEmployee of the Month - Samsung Semiconductor India Research
Employee of the Month - Samsung Semiconductor India Research
 
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Greater Noida 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...
VIP Call Girls Service Cuttack Aishwarya 8250192130 Independent Escort Servic...
 
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
 
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service BhilaiVIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
 
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
 
The Impact of Socioeconomic Status on Education.pdf
The Impact of Socioeconomic Status on Education.pdfThe Impact of Socioeconomic Status on Education.pdf
The Impact of Socioeconomic Status on Education.pdf
 

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