
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - Collections
Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option).
Collections may be strict or lazy. Lazy collections have elements that may not consume memory until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of the reference can change) or immutable (the thing that a reference refers to is never changed). Note that immutable collections may contain mutable items.
For some problems, mutable collections work better, and for others, immutable collections work better. When in doubt, it is better to start with an immutable collection and change it later if you need mutable ones.
This chapter throws light on the most commonly used collection types and most frequently used operations over those collections.
Sr.No | Collections with Description |
---|---|
1 |
Scala's List[T] is a linked list of type T. |
2 |
A set is a collection of pairwise different elements of the same type. |
3 |
A Map is a collection of key/value pairs. Any value can be retrieved based on its key. |
4 |
Unlike an array or list, a tuple can hold objects with different types. |
5 |
Option[T] provides a container for zero or one element of a given type. |
6 |
An iterator is not a collection, but rather a way to access the elements of a collection one by one. |
Scala Lists
List is an ordered collection of elements. It is immutable by default. The following is the syntax for declaring a List variable -
val fruits: List[String] = List("Apple", "Banana", "Cherry")
Example
object Demo { def main(args: Array[String]) = { val fruits: List[String] = List("Apple", "Banana", "Cherry") // Print the list println(fruits) // Access elements println(fruits(0)) println(fruits(1)) println(fruits(2)) } }
Output
List(Apple, Banana, Cherry) Apple Banana Cherry
Scala Sets
Set is a collection of unique elements. It is immutable by default. The following is the syntax for declaring a Set variable -
val fruits: Set[String] = Set("Apple", "Banana", "Cherry")
Example
object Demo { def main(args: Array[String]) = { val fruits: Set[String] = Set("Apple", "Banana", "Cherry") // Print the set println(fruits) // Check membership println(fruits.contains("Apple")) println(fruits.contains("Grapes")) } }
Output
Set(Apple, Banana, Cherry) true false
Scala Maps
Map is a collection of key-value pairs. It is immutable by default. The following is the syntax for declaring a Map variable -
val colors: Map[String, String] = Map("red" -> "#FF0000", "green" -> "#00FF00", "blue" -> "#0000FF")
Example
object Demo { def main(args: Array[String]) = { val colors: Map[String, String] = Map("red" -> "#FF0000", "green" -> "#00FF00", "blue" -> "#0000FF") // Print the map println(colors) // Access elements println(colors("red")) println(colors("green")) println(colors("blue")) } }
Output
Map(red -> #FF0000, green -> #00FF00, blue -> #0000FF) #FF0000 #00FF00 #0000FF
Scala Tuples
Tuple is a collection of elements of different types. The following is the syntax for declaring a Tuple variable -
val tuple: (String, Int, Boolean) = ("Scala", 42, true)
Example
object Demo { def main(args: Array[String]) = { val tuple: (String, Int, Boolean) = ("Scala", 42, true) // Print the tuple println(tuple) // Access elements println(tuple._1) println(tuple._2) println(tuple._3) } }
Output
(Scala, 42, true) Scala 42 true
Scala Options
Option is a container for zero or one element of a given type. The following is the syntax for declaring an Option variable -
val someValue: Option[Int] = Some(42) val noneValue: Option[Int] = None
Example
object Demo { def main(args: Array[String]) = { val someValue: Option[Int] = Some(42) val noneValue: Option[Int] = None // Print the options println(someValue) println(noneValue) // Access elements println(someValue.getOrElse(0)) println(noneValue.getOrElse(0)) } }
Output
Some(42) None 42 0
Scala Iterators
Iterator is not a collection, but rather a way to access the elements of a collection one by one. The following is the syntax for declaring an Iterator variable -
val iterator: Iterator[Int] = Iterator(1, 2, 3, 4, 5)
Example
object Demo { def main(args: Array[String]) = { val iterator: Iterator[Int] = Iterator(1, 2, 3, 4, 5) // Print the iterator println(iterator) // Iterate through elements while (iterator.hasNext) { println(iterator.next()) } } }
Output
non-empty iterator 1 2 3 4 5
Scala Vectors
Vector is an immutable indexed sequence that provides fast random access and updates. The following is the syntax for declaring a Vector variable -
val numbers: Vector[Int] = Vector(1, 2, 3, 4, 5)
Example
object Demo { def main(args: Array[String]) = { val numbers: Vector[Int] = Vector(1, 2, 3, 4, 5) // Print the vector println(numbers) // Access elements println(numbers(0)) println(numbers(1)) println(numbers(2)) println(numbers(3)) println(numbers(4)) } }
Output
Vector(1, 2, 3, 4, 5) 1 2 3 4 5
Scala Queues
Queue is a collection that follows the FIFO (First-In-First-Out) principle. The following is the syntax for declaring a Queue variable.
import scala.collection.immutable.Queue val queue: Queue[Int] = Queue(1, 2, 3)
Example
import scala.collection.immutable.Queue object Demo { def main(args: Array[String]) = { val queue: Queue[Int] = Queue(1, 2, 3) // Print the queue println(queue) // Enqueue an element val enqueueQueue = queue.enqueue(4) println(enqueueQueue) // Dequeue an element val (dequeueElement, dequeueQueue) = queue.dequeue println(dequeueElement) println(dequeueQueue) } }
Output
Queue(1, 2, 3) Queue(1, 2, 3, 4) 1 Queue(2, 3, 4)
Scala Stacks
Stack is a collection that follows the LIFO (Last-In-First-Out) principle. The following is the syntax for declaring a Stack variable -
import scala.collection.mutable.Stack val stack: Stack[Int] = Stack(1, 2, 3)
Example
import scala.collection.mutable.Stack object Demo { def main(args: Array[String]) = { val stack: Stack[Int] = Stack(1, 2, 3) // Print the stack println(stack) // Push an element stack.push(4) println(stack) // Pop an element val popElement = stack.pop println(popElement) println(stack) } }
Output
Stack(1, 2, 3) Stack(1, 2, 3, 4) 4 Stack(1, 2, 3)
Scala Sequences
Seq is a trait for indexed collections. It can be either mutable or immutable. The following is the syntax for declaring a Seq variable -
val seq: Seq[Int] = Seq(1, 2, 3, 4, 5)
Example
object Demo { def main(args: Array[String]) = { val seq: Seq[Int] = Seq(1, 2, 3, 4, 5) // Print the sequence println(seq) // Access elements println(seq(0)) println(seq(1)) println(seq(2)) println(seq(3)) println(seq(4)) } }
Output
Seq(1, 2, 3, 4, 5) 1 2 3 4 5
Scala Ranges
Range represents a sequence of integers and is commonly used in for-loops. The following is the syntax for declaring a Range variable.
val range: Range = 1 to 5
Example
object Demo { def main(args: Array[String]) = { val range: Range = 1 to 5 // Print the range println(range) // Iterate through the range range.foreach(println) } }
Output
Range(1, 2, 3, 4, 5) 1 2 3 4 5
Note that you need to save the above each program as Demo.scala. The following commands are used to compile and execute this program.
> scalac Demo.scala > scala Demo
Then you can see your outputs.
Scala Collections Summary
- Scala collections are containers that hold a sequence of elements and provide various operations and methods for these collections.
- There are various types of collections in Scala, like, Lists, Sets, Maps, Tuples, Options, Iterators, Vectors, Queues, Stacks, Sequences, and Ranges.
- Collections can be either mutable or immutable. Immutable collections cannot be modified after these are created. Whereas mutable collections can be changed anytime.
- Common operations on collections are: adding, removing, accessing, and transforming elements.
- Scala collections also support higher-order functions like, map, filter, and foreach for functional programming.