SlideShare a Scribd company logo
1 of 23
Collections
In
Scala
Collections
In
Scala
Harsh Sharma
Software Consultant - Trainee
Knoldus Software LLP
Harsh Sharma
Software Consultant - Trainee
Knoldus Software LLP
AgendaAgenda
● Why Collections? I love collections
● Introduction to Scala collections
● Code examples
● Why Collections? I love collections
● Introduction to Scala collections
● Code examples
Why collections?Why collections?
No complicated looping structures and recursions
Side-effect-free operations
No interference between iterators and collections
No complicated looping structures and recursions
Side-effect-free operations
No interference between iterators and collections
Defining collectionsDefining collections
I love collections – Why?
Immutable?? Mutable??
Lets begin the collection
Lists
scala> val Numbers = List(1, 2, 3, 4)
numbers: List[Int] = List(1, 2, 3, 4)
Numbers :+= 5 //error of reassignment
Numbers ++= List(6,7,8) //error of reassignment
Numbers ++= List(9,”Harsh”)//type mismatch
Lets begin the collection
Sets
Sets have no duplicates
scala> var Numbers = Set(1, 1, 2)
res0: scala.collection.immutable.Set[Int] = Set(1, 2)
Numbers += “Knoldus” // type mismatch error
Numbers += 2 // blank or no output having 1 and 2 as elements
Numbers += 3 //scala.collection.immutable.Set[Int] =
Set(1, 2, 3)
Lets begin the collection
Tuple
A tuple groups together simple logical collections of
items without using a class.
scala> val hostPort = ("localhost", 80)
hostPort: (String, Int) = (localhost, 80)
Lets begin the collection
Tuples do not have named accessors, like case classes
Just have their position as 1-based
Have limit of 22 elements
scala> hostPort._1
res0: String = localhost
scala> hostPort._2
res1: Int = 80
Lets begin the collection
Tuples satisfies the pattern matching nicely
hostPort match {
case ("localhost", port) => ...
case (host, port) => ...
}
Lets begin the collection
Special sauce to create tuple of two elements
scala> 1 -> 2
res0: (Int, Int) = (1,2)
scala> "Harsh"->"Sharma"->"Khandal"
res4: ((String, String), String) = ((Harsh,Sharma),Khandal)
Lets begin the collection
● Map can hold basic datatypes
● Collection of tuples
● Can contain maps and functions as values
● Map(1 -> 2)
Map("foo" -> "bar")
● Map(1 -> Map("foo" -> "bar"))
● Map("timesTwo" -> { timesTwo(_) })
Lets begin the collection
Option[T] is used when the method might not return what we ask
for
● scala> val numbers = Map("one" -> 1, "two" -> 2)
numbers: scala.collection.immutable.Map[java.lang.String,Int] =
Map(one -> 1, two -> 2)
● scala> numbers.get("two")
res0: Option[Int] = Some(2)
● scala> numbers.get("three")
res1: Option[Int] = None
Functional combinators
map: evaluates a function over each element of list
scala> val numbers=List(1,2,3,4)
numbers: List[Int] = List(1, 2, 3, 4)
scala> numbers.map((i: Int) => i * 2)
res1: List[Int] = List(2, 4, 6, 8)
foreach: A kind of map but returns nothing
scala> val doubled = numbers.foreach((i: Int) => i * 2)
doubled: Unit = ()
Functional combinators
filter: removes elements when function we pass evaluates to
false
scala> numbers.filter((i: Int) => i % 2 == 0)
res0: List[Int] = List(2, 4)
zip: Zips contents of multiple lists into one single list
scala> List(1, 2, 3).zip(List("a", "b", "c"))
res0: List[(Int, String)] = List((1,a), (2,b), (3,c))
Functional combinators
partition: splits a list based on where it falls with respect to a
predicate function.
scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> numbers.partition(_ % 2 == 0)
res0: (List[Int], List[Int]) = (List(2, 4, 6, 8, 10),List(1, 3, 5, 7, 9))
find: returns the first element of a collection that matches a
function.
scala> numbers.find((i: Int) => i > 5)
res0: Option[Int] = Some(6)
Functional combinators
drop: drops the first i elements
scala> numbers.drop(5)
res0: List[Int] = List(6, 7, 8, 9, 10)
● dropWhile: removes the first elements that match a predicate
function
scala> numbers.dropWhile(_ % 2 != 0)
res0: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10)
Functional combinators
foldLeft: value passed as argument is the initial value and m is
the accumulator
scala> numbers.foldLeft(0)((m: Int, n: Int) => m + n)
res0: Int = 55
– scala> numbers.foldLeft(0) { (m: Int, n: Int) => println("m: " + m + " n: " + n); m + n }
Functional combinators
scala> numbers.foldLeft(0) { (m: Int, n: Int) => println("m: " + m + " n: " + n); m + n }
m: 0 n: 1
m: 1 n: 2
m: 3 n: 3
m: 6 n: 4
m: 10 n: 5
m: 15 n: 6
m: 21 n: 7
m: 28 n: 8
m: 36 n: 9
m: 45 n: 10
res0: Int = 55
Functional combinators
foldRight: As same as foldLeft, but performs from opposite direction
scala> numbers.foldRight(0) { (m: Int, n: Int) => println("m: " + m + " n: " + n); m + n }
m: 10 n: 0
m: 9 n: 10
m: 8 n: 19
m: 7 n: 27
m: 6 n: 34
m: 5 n: 40
m: 4 n: 45
m: 3 n: 49
m: 2 n: 52
m: 1 n: 54
res0: Int = 55
Functional combinators
flatten: collapses nested structures
–
– scala> List(List(1, 2), List(3, 4)).flatten
– res0: List[Int] = List(1, 2, 3, 4)
Collections In Scala

More Related Content

What's hot

High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
Johan Tibell
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
Johan Tibell
 

What's hot (19)

Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
 
Data import-cheatsheet
Data import-cheatsheetData import-cheatsheet
Data import-cheatsheet
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
 
Python list
Python listPython list
Python list
 

Similar to Collections In Scala

Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee
 

Similar to Collections In Scala (20)

Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Abstract Algebra and Category Theory
Abstract Algebra and Category Theory
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
Scala Collections
Scala CollectionsScala Collections
Scala Collections
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
(Ai lisp)
(Ai lisp)(Ai lisp)
(Ai lisp)
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
Practical cats
Practical catsPractical cats
Practical cats
 

More from Knoldus Inc.

More from Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 

Collections In Scala

  • 1. Collections In Scala Collections In Scala Harsh Sharma Software Consultant - Trainee Knoldus Software LLP Harsh Sharma Software Consultant - Trainee Knoldus Software LLP
  • 2. AgendaAgenda ● Why Collections? I love collections ● Introduction to Scala collections ● Code examples ● Why Collections? I love collections ● Introduction to Scala collections ● Code examples
  • 3. Why collections?Why collections? No complicated looping structures and recursions Side-effect-free operations No interference between iterators and collections No complicated looping structures and recursions Side-effect-free operations No interference between iterators and collections
  • 7. Lets begin the collection Lists scala> val Numbers = List(1, 2, 3, 4) numbers: List[Int] = List(1, 2, 3, 4) Numbers :+= 5 //error of reassignment Numbers ++= List(6,7,8) //error of reassignment Numbers ++= List(9,”Harsh”)//type mismatch
  • 8. Lets begin the collection Sets Sets have no duplicates scala> var Numbers = Set(1, 1, 2) res0: scala.collection.immutable.Set[Int] = Set(1, 2) Numbers += “Knoldus” // type mismatch error Numbers += 2 // blank or no output having 1 and 2 as elements Numbers += 3 //scala.collection.immutable.Set[Int] = Set(1, 2, 3)
  • 9. Lets begin the collection Tuple A tuple groups together simple logical collections of items without using a class. scala> val hostPort = ("localhost", 80) hostPort: (String, Int) = (localhost, 80)
  • 10. Lets begin the collection Tuples do not have named accessors, like case classes Just have their position as 1-based Have limit of 22 elements scala> hostPort._1 res0: String = localhost scala> hostPort._2 res1: Int = 80
  • 11. Lets begin the collection Tuples satisfies the pattern matching nicely hostPort match { case ("localhost", port) => ... case (host, port) => ... }
  • 12. Lets begin the collection Special sauce to create tuple of two elements scala> 1 -> 2 res0: (Int, Int) = (1,2) scala> "Harsh"->"Sharma"->"Khandal" res4: ((String, String), String) = ((Harsh,Sharma),Khandal)
  • 13. Lets begin the collection ● Map can hold basic datatypes ● Collection of tuples ● Can contain maps and functions as values ● Map(1 -> 2) Map("foo" -> "bar") ● Map(1 -> Map("foo" -> "bar")) ● Map("timesTwo" -> { timesTwo(_) })
  • 14. Lets begin the collection Option[T] is used when the method might not return what we ask for ● scala> val numbers = Map("one" -> 1, "two" -> 2) numbers: scala.collection.immutable.Map[java.lang.String,Int] = Map(one -> 1, two -> 2) ● scala> numbers.get("two") res0: Option[Int] = Some(2) ● scala> numbers.get("three") res1: Option[Int] = None
  • 15. Functional combinators map: evaluates a function over each element of list scala> val numbers=List(1,2,3,4) numbers: List[Int] = List(1, 2, 3, 4) scala> numbers.map((i: Int) => i * 2) res1: List[Int] = List(2, 4, 6, 8) foreach: A kind of map but returns nothing scala> val doubled = numbers.foreach((i: Int) => i * 2) doubled: Unit = ()
  • 16. Functional combinators filter: removes elements when function we pass evaluates to false scala> numbers.filter((i: Int) => i % 2 == 0) res0: List[Int] = List(2, 4) zip: Zips contents of multiple lists into one single list scala> List(1, 2, 3).zip(List("a", "b", "c")) res0: List[(Int, String)] = List((1,a), (2,b), (3,c))
  • 17. Functional combinators partition: splits a list based on where it falls with respect to a predicate function. scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> numbers.partition(_ % 2 == 0) res0: (List[Int], List[Int]) = (List(2, 4, 6, 8, 10),List(1, 3, 5, 7, 9)) find: returns the first element of a collection that matches a function. scala> numbers.find((i: Int) => i > 5) res0: Option[Int] = Some(6)
  • 18. Functional combinators drop: drops the first i elements scala> numbers.drop(5) res0: List[Int] = List(6, 7, 8, 9, 10) ● dropWhile: removes the first elements that match a predicate function scala> numbers.dropWhile(_ % 2 != 0) res0: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10)
  • 19. Functional combinators foldLeft: value passed as argument is the initial value and m is the accumulator scala> numbers.foldLeft(0)((m: Int, n: Int) => m + n) res0: Int = 55 – scala> numbers.foldLeft(0) { (m: Int, n: Int) => println("m: " + m + " n: " + n); m + n }
  • 20. Functional combinators scala> numbers.foldLeft(0) { (m: Int, n: Int) => println("m: " + m + " n: " + n); m + n } m: 0 n: 1 m: 1 n: 2 m: 3 n: 3 m: 6 n: 4 m: 10 n: 5 m: 15 n: 6 m: 21 n: 7 m: 28 n: 8 m: 36 n: 9 m: 45 n: 10 res0: Int = 55
  • 21. Functional combinators foldRight: As same as foldLeft, but performs from opposite direction scala> numbers.foldRight(0) { (m: Int, n: Int) => println("m: " + m + " n: " + n); m + n } m: 10 n: 0 m: 9 n: 10 m: 8 n: 19 m: 7 n: 27 m: 6 n: 34 m: 5 n: 40 m: 4 n: 45 m: 3 n: 49 m: 2 n: 52 m: 1 n: 54 res0: Int = 55
  • 22. Functional combinators flatten: collapses nested structures – – scala> List(List(1, 2), List(3, 4)).flatten – res0: List[Int] = List(1, 2, 3, 4)