scalabeginner

Map and HashMap Operations

Work with Scala Maps: create, update, merge, transform, and use default values.

scala
import scala.collection.mutable

@main def run(): Unit =
  // Immutable Map
  val config = Map(
    "host" -> "localhost",
    "port" -> "8080",
    "db"   -> "myapp"
  )

  println(config("host"))           // localhost
  println(config.get("missing"))    // None
  println(config.getOrElse("timeout", "30"))  // 30

  // Add/update (returns new map)
  val updated = config + ("timeout" -> "60") + ("port" -> "9090")
  println(updated)

  // Remove
  val reduced = config - "db"
  println(reduced)

  // Map with default
  val counter = Map.empty[String, Int].withDefaultValue(0)
  val c1 = counter + ("a" -> (counter("a") + 1))
  println(s"Counter a: ${c1("a")}")  // 1

  // Transformations
  val prices = Map("apple" -> 1.5, "banana" -> 0.75, "cherry" -> 3.0)
  val discounted = prices.map((k, v) => k -> v * 0.9)
  val expensive = prices.filter((_, v) => v > 1.0)
  println(s"Discounted: $discounted")
  println(s"Expensive: $expensive")

  // Merge maps
  val defaults = Map("color" -> "blue", "size" -> "M", "qty" -> "1")
  val overrides = Map("size" -> "L", "qty" -> "3")
  val merged = defaults ++ overrides
  println(s"Merged: $merged")

  // groupBy to create map
  val words = "the quick brown fox jumps over the lazy dog".split(" ")
  val byLength = words.groupBy(_.length)
  byLength.foreach((len, ws) => println(s"Length $len: ${ws.mkString(", ")}"))

  // Mutable map
  val cache = mutable.Map.empty[String, Int]
  cache("x") = 10
  cache("y") = 20
  cache.getOrElseUpdate("z", { println("Computing z"); 30 })
  cache.getOrElseUpdate("z", { println("Won't run"); 99 })
  println(s"Cache: $cache")

  // Map to list of tuples and back
  val tuples = prices.toList.sortBy(_._2)
  val backToMap = tuples.toMap
  println(s"Sorted: $tuples")

Use Cases

  • Configuration management
  • Word frequency counting
  • Cache implementation

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.