Skip to main content

Platforms and Technology

Scala: mutable data structure

mutable

Scala, a programming language that combines object-oriented and functional programming paradigms, provides a variety of mutable data structures. Mutable collections such as ArrayBuffer and HashMap facilitate in-place modifications, making them well-suited for situations demanding high-performance, mutable structures. They present a conventional alternative, providing a mutable counterpart to their immutable equivalents.

All the mutable scala collections will be under this package – scala.collection.mutable.

Let’s explore some mutable data structures.

1. Mutable List (ListBuffer):

scala.collection.mutable.ListBuffer is a mutable list implementation in Scala. Unlike immutable lists, elements in a ListBuffer can be added or removed.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import scala.collection.mutable.ListBuffer
valmutableList=ListBuffer(1, 2, 3)
mutableList += 4// Appending an element
mutableList -= 2// Removing an element
import scala.collection.mutable.ListBuffer val mutableList = ListBuffer(1, 2, 3) mutableList += 4 // Appending an element mutableList -= 2 // Removing an element
import scala.collection.mutable.ListBuffer

val mutableList = ListBuffer(1, 2, 3)
mutableList += 4 // Appending an element
mutableList -= 2 // Removing an element

Mutable lists, implemented as ListBuffer, are beneficial when frequent modifications to the list are required. They offer efficient append and removal operations.

Common Operations on Mutable Lists (ListBuffer):

  • Appending and Removing Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mutableList += 5// Append
mutableList -= 3// Remove
mutableList += 5 // Append mutableList -= 3 // Remove
mutableList += 5 // Append 
mutableList -= 3 // Remove
  • Inserting Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mutableList.insert(2, 10)// Insert 10 at index 2
mutableList.insert(2, 10) // Insert 10 at index 2
mutableList.insert(2, 10) // Insert 10 at index 2
  • Updating Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mutableList(1)=22// Update element at index 1
mutableList(1) = 22 // Update element at index 1
mutableList(1) = 22 // Update element at index 1
  • Converting to Immutable List:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valimmutableList= mutableList.toList // Convert to immutable list
val immutableList = mutableList.toList // Convert to immutable list
val immutableList = mutableList.toList // Convert to immutable list
  • Iterating Through Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for(element <- mutableList){
// Process each element
}
for (element <- mutableList) { // Process each element }
for (element <- mutableList) { 
// Process each element
 }

Mutable lists can be convenient in scenarios where the structure of the list needs to be altered frequently.  In functional programming, immutable lists are generally preferred for their safety and predictability. Consider using mutable lists when performance requirements or specific use cases warrant their use.

2. Mutable Set:

scala.collection.mutable.Set is a mutable set implementation in Scala. It allows elements to be added or removed, providing flexibility for dynamic modifications.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import scala.collection.mutable.Set
valmutableSet=Set(1, 2, 3)
mutableSet += 4// Adding an element
mutableSet -= 2// Removing an element
import scala.collection.mutable.Set val mutableSet = Set(1, 2, 3) mutableSet += 4 // Adding an element mutableSet -= 2 // Removing an element
import scala.collection.mutable.Set

val mutableSet = Set(1, 2, 3)
mutableSet += 4 // Adding an element
mutableSet -= 2 // Removing an element

Mutable sets offer flexibility when dynamic modifications to the set are necessary.

Common Operations on Mutable Sets:

  • Adding and Removing Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mutableSet += 5// Add element
mutableSet -= 3// Remove element
mutableSet += 5 // Add element mutableSet -= 3 // Remove element
mutableSet += 5 // Add element
mutableSet -= 3 // Remove element
  • Checking Membership:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valcontainsTwo= mutableSet.contains(2)// true
val containsTwo = mutableSet.contains(2) // true
val containsTwo = mutableSet.contains(2) // true
  • Union, Intersection, and Difference:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valanotherSet=Set(3, 4, 5)
valunionSet= mutableSet ++ anotherSet // Union
valintersectionSet= mutableSet.intersect(anotherSet)// Intersection
valdifferenceSet= mutableSet.diff(anotherSet)// Difference
val anotherSet = Set(3, 4, 5) val unionSet = mutableSet ++ anotherSet // Union val intersectionSet = mutableSet.intersect(anotherSet) // Intersection val differenceSet = mutableSet.diff(anotherSet) // Difference
val anotherSet = Set(3, 4, 5)
val unionSet = mutableSet ++ anotherSet // Union
val intersectionSet = mutableSet.intersect(anotherSet) // Intersection
val differenceSet = mutableSet.diff(anotherSet) // Difference
  • Converting to Immutable Set:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valimmutableSet= mutableSet.toSet // Convert to immutable set
val immutableSet = mutableSet.toSet // Convert to immutable set
val immutableSet = mutableSet.toSet // Convert to immutable set
  • Iterating Through Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for(element <- mutableSet){
// Process each element
}
for (element <- mutableSet) { // Process each element }
for (element <- mutableSet) {
  // Process each element
}

Mutable sets can be useful in scenarios where the set’s structure needs frequent modifications. In functional programming, immutable sets are generally preferred for their safety and predictability. The choice between mutable and immutable sets depends on specific use cases and performance considerations.

3. Mutable Map:

scala.collection.mutable.Map is a mutable map implementation in Scala. It allows for adding, updating, and removing key-value pairs, providing flexibility for dynamic modifications.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import scala.collection.mutable.Map
valmutableMap=Map("one" ->1, "two" ->2, "three" ->3)
mutableMap += ("four" ->4)// Adding an entry
mutableMap -= "two"// Removing an entry
mutableMap("three")=33// Updating a value
import scala.collection.mutable.Map val mutableMap = Map("one" -> 1, "two" -> 2, "three" -> 3) mutableMap += ("four" -> 4) // Adding an entry mutableMap -= "two" // Removing an entry mutableMap("three") = 33 // Updating a value
import scala.collection.mutable.Map 

val mutableMap = Map("one" -> 1, "two" -> 2, "three" -> 3) 
mutableMap += ("four" -> 4) // Adding an entry 
mutableMap -= "two" // Removing an entry 
mutableMap("three") = 33 // Updating a value

Mutable maps offer flexibility when dynamic modifications to the key-value pairs are necessary.

Common Operations on Mutable Maps:

  • Adding and Removing Entries:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mutableMap += ("five" ->5)// Add entry
mutableMap -= "three"// Remove entry
mutableMap += ("five" -> 5) // Add entry mutableMap -= "three" // Remove entry
mutableMap += ("five" -> 5) // Add entry 
mutableMap -= "three" // Remove entry
  • Updating Values:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mutableMap("two")=22// Update value
mutableMap("two") = 22 // Update value
mutableMap("two") = 22 // Update value
  • Checking Key Existence:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valcontainsTwoKey= mutableMap.contains("two")// true
val containsTwoKey = mutableMap.contains("two") // true
val containsTwoKey = mutableMap.contains("two") // true
  • Merging Maps:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
val anotherMap = Map("three" ->33, "four" ->4)
mutableMap ++= anotherMap // Merge maps
val anotherMap = Map("three" -> 33, "four" -> 4) mutableMap ++= anotherMap // Merge maps
val anotherMap = Map("three" -> 33, "four" -> 4) 
mutableMap ++= anotherMap // Merge maps
  • Converting to Immutable Map:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
valimmutableMap= mutableMap.toMap // Convert to immutable map
val immutableMap = mutableMap.toMap // Convert to immutable map
val immutableMap = mutableMap.toMap // Convert to immutable map
  • Iterating Through Entries:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for((key, value)<- mutableMap){
// Process each key-value pair
}
for ((key, value) <- mutableMap) { // Process each key-value pair }
for ((key, value) <- mutableMap) { 
// Process each key-value pair 
}

Mutable maps can be useful in scenarios where the map’s structure needs frequent modifications. In functional programming, immutable maps are generally preferred for their safety and predictability. The choice between mutable and immutable maps depends on specific use cases and performance considerations.

4. Mutable Buffer:

scala.collection.mutable.Buffer is a trait in Scala that represents a mutable, indexed sequence. It extends the scala.collection.mutable.Seq trait, providing a set of methods for adding, updating, and removing elements at specific indices.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import scala.collection.mutable.Buffer
valmutableBuffer:Buffer[Int]=Buffer(1, 2, 3)
mutableBuffer += 4// Appending an element
mutableBuffer(1)=22// Updating an element
mutableBuffer.remove(2)// Removing an element
import scala.collection.mutable.Buffer val mutableBuffer: Buffer[Int] = Buffer(1, 2, 3) mutableBuffer += 4 // Appending an element mutableBuffer(1) = 22 // Updating an element mutableBuffer.remove(2) // Removing an element
import scala.collection.mutable.Buffer

val mutableBuffer: Buffer[Int] = Buffer(1, 2, 3)
mutableBuffer += 4 // Appending an element
mutableBuffer(1) = 22 // Updating an element
mutableBuffer.remove(2) // Removing an element

Common Operations on Mutable Buffer:

  • Appending Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mutableBuffer += 5// Append an element
mutableBuffer += 5 // Append an element
mutableBuffer += 5 // Append an element
  • Updating Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mutableBuffer(1)=22// Update element at index 1
mutableBuffer(1) = 22 // Update element at index 1
mutableBuffer(1) = 22 // Update element at index 1
  • Removing Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mutableBuffer.remove(2)// Remove element at index 2
mutableBuffer.remove(2) // Remove element at index 2
mutableBuffer.remove(2) // Remove element at index 2
  • Iterating Through Elements:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
for(element <- mutableBuffer){
// Process each element
}
for (element <- mutableBuffer) { // Process each element }
for (element <- mutableBuffer) {
  // Process each element
}

Mutable buffers, represented by scala.collection.mutable.Buffer, provide a flexible and efficient way to manage dynamic modifications to a sequence. They are particularly useful when frequent changes to the content and structure of the collection are required.

Mutable Collections (from scala.collection.mutable package):

Scala provides various other mutable collections like ArrayBuffer, HashMap, Queue, LinkedList, etc.

References:

Here are the Spark documents delving further into the creation of mutable data structures in Scala.

Official Spark Documentation:  
https://docs.scala-lang.org/overviews/collections/overview.html
https://www.scala-lang.org/api/2.12.9/scala/collection/mutable/Buffer.html
Immutable blog: Scala: Immutable data structure / Blogs / Perficient

In conclusion, Mutable data structures in Scala provide developers with the ability to make dynamic changes to the structure and content of collections. They offer flexibility but require careful management of mutable state to avoid unintended side effects, especially in concurrent or parallel programming.

Tags

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Saranya Sridhar

Saranya is an Technical Consultant at Perficient, exploring the stages of Big Data. Her experience includes Spark, Scala, SQL, Databricks, Java, and BI tools like Tableau, Spotfire, and Power BI. She passionately delves into emerging technologies.

More from this Author

Follow Us