Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Map

In Scala, Map is a collection of key-value pairs where each key is unique. Scala provides a wide variety of methods to create, transform, query, and manipulate maps. Here's a comprehensive overview of the most common functions available for Map in Scala:

Creating Maps

  • apply: Creates a map from given key-value pairs.

    val map = Map(1 -> "one", 2 -> "two", 3 -> "three")
    
  • empty: Creates an empty map.

    val emptyMap = Map.empty[Int, String]
    

Basic Operations

  • get: Retrieves the value associated with a key, returning Option.

    val value = map.get(2) // Some("two")
    val missing = map.get(4) // None
    
  • apply: Retrieves the value associated with a key, throwing an exception if the key is not found.

    val value = map(2) // "two"
    
  • contains: Checks if the map contains a key.

    val exists = map.contains(2) // true
    val notExists = map.contains(4) // false
    
  • isEmpty: Checks if the map is empty.

    val empty = map.isEmpty // false
    
  • size: Returns the size of the map.

    val size = map.size // 3
    

Adding and Removing Elements

  • +: Adds a key-value pair to the map.

    val newMap = map + (4 -> "four")
    
  • -: Removes a key-value pair by key.

    val smallerMap = map - 2
    
  • ++: Adds multiple key-value pairs to the map.

    val morePairs = map ++ Map(4 -> "four", 5 -> "five")
    
  • --: Removes multiple keys from the map.

    val fewerPairs = map -- List(1, 2)
    

Transformations

  • map: Transforms each key-value pair using a function.

    val mapped = map.map { case (k, v) => (k, v.toUpperCase) }
    
  • flatMap: Transforms each key-value pair using a function that returns an iterable, and flattens the result.

    val flatMapped = map.flatMap { case (k, v) => List(k -> v, k -> v.toUpperCase) }
    
  • collect: Transforms key-value pairs using a partial function.

    val collected = map.collect { case (k, v) if k % 2 == 0 => (k, v.toUpperCase) }
    

Filtering

  • filter: Selects key-value pairs that satisfy a predicate.

    val filtered = map.filter { case (k, v) => k % 2 == 0 }
    
  • filterKeys: Selects key-value pairs whose keys satisfy a predicate.

    val filteredKeys = map.filterKeys(_ % 2 == 0)
    
  • filterNot: Selects key-value pairs that do not satisfy a predicate.

    val filterNot = map.filterNot { case (k, v) => k % 2 == 0 }
    

Aggregation

  • foldLeft: Aggregates values from left to right.

    val foldedLeft = map.foldLeft("") { case (acc, (k, v)) => acc + v }
    
  • foldRight: Aggregates values from right to left.

    val foldedRight = map.foldRight("") { case ((k, v), acc) => acc + v }
    

Merging Maps

  • ++: Merges two maps, with the second map overwriting keys in the first map.
    val merged = map ++ Map(2 -> "TWO", 4 -> "four")
    

Submaps and Key Sets

  • keys: Returns an iterable of all keys.

    val keys = map.keys // Iterable(1, 2, 3)
    
  • values: Returns an iterable of all values.

    val values = map.values // Iterable("one", "two", "three")
    
  • keySet: Returns a set of all keys.

    val keySet = map.keySet // Set(1, 2, 3)
    

Transformations by Keys and Values

  • mapValues: Transforms the values using a function.

    val mappedValues = map.mapValues(_.toUpperCase)
    
  • transform: Transforms both keys and values using a function.

    val transformed = map.transform { case (k, v) => v.toUpperCase }
    

Grouping

  • groupBy: Groups the map by a function applied to the keys.
    val groupedByMod = map.groupBy { case (k, v) => k % 2 }
    

Conversion

  • toList: Converts the map to a list of key-value pairs.

    val list = map.toList // List((1, "one"), (2, "two"), (3, "three"))
    
  • toArray: Converts the map to an array of key-value pairs.

    val array = map.toArray // Array((1, "one"), (2, "two"), (3, "three"))
    
  • toSeq: Converts the map to a sequence of key-value pairs.

    val seq = map.toSeq // Seq((1, "one"), (2, "two"), (3, "three"))
    

Example Usage

Here are some example usages of the above functions:

val map = Map(1 -> "one", 2 -> "two", 3 -> "three")

// Basic Operations
val value = map.get(2) // Some("two")
val missing = map.get(4) // None
val exists = map.contains(2) // true
val size = map.size // 3

// Adding and Removing Elements
val newMap = map + (4 -> "four") // Map(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four")
val smallerMap = map - 2 // Map(1 -> "one", 3 -> "three")
val morePairs = map ++ Map(4 -> "four", 5 -> "five") // Map(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four", 5 -> "five")
val fewerPairs = map -- List(1, 2) // Map(3 -> "three")

// Transformations
val mapped = map.map { case (k, v) => (k, v.toUpperCase) } // Map(1 -> "ONE", 2 -> "TWO", 3 -> "THREE")
val flatMapped = map.flatMap { case (k, v) => List(k -> v, k -> v.toUpperCase) } // Map(1 -> "one", 1 -> "ONE", 2 -> "two", 2 -> "TWO", 3 -> "three", 3 -> "THREE")
val collected = map.collect { case (k, v) if k % 2 == 0 => (k, v.toUpperCase) } // Map(2 -> "TWO")

// Filtering
val filtered = map.filter { case (k, v) => k % 2 == 0 } // Map(2 -> "two")
val filteredKeys = map.filterKeys(_ % 2 == 0) // Map(2 -> "two")
val filterNot = map.filterNot { case (k, v) => k % 2 == 0 } // Map(1 -> "one", 3 -> "three")

// Aggregation
val foldedLeft = map.foldLeft("") { case (acc, (k, v)) => acc + v } // "onetwothree"
val foldedRight = map.foldRight("") { case ((k, v), acc) => acc + v } // "threetwoone"

// Merging Maps
val merged = map ++ Map(2 -> "TWO", 4 -> "four") // Map(1 -> "one", 2 -> "TWO", 3 -> "three", 4 -> "four")

// Submaps and Key Sets
val keys = map.keys // Iterable(1, 2, 3)
val values = map.values // Iterable("one", "two", "three")
val keySet = map.keySet // Set(1, 2, 3)

// Transformations by Keys and Values
val mappedValues = map.mapValues(_.toUpperCase) // Map(1 -> "ONE", 2 -> "TWO", 3 -> "THREE")
val transformed = map.transform { case (k, v) => v.toUpperCase } // Map(1 -> "ONE", 2 -> "TWO", 3 -> “THREE”)

// Grouping
val groupedByMod = map.groupBy { case (k, v) => k % 2 } // Map(0 -> Map(2 -> “two”), 1 -> Map(1 -> “one”, 3 -> “three”))

// Conversion
val list = map.toList // List((1, “one”), (2, “two”), (3, “three”))
val array = map.toArray // Array((1, “one”), (2, “two”), (3, “three”))
val seq = map.toSeq // Seq((1, “one”), (2, “two”), (3, “three”))