scalabeginner
Map and HashMap Operations
Work with Scala Maps: create, update, merge, transform, and use default values.
scalaPress ⌘/Ctrl + Shift + C to copy
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.
scalabeginner
Advanced Map Operations
Advanced Map usage: merge, transform, groupMapReduce, default values, and nested maps.
Best for: Data aggregation and grouping
#scala#map
scalabeginner
Collections Map Filter Fold Operations
Master Scala collections: map, flatMap, filter, fold, groupBy, partition, and zip operations.
Best for: Data transformation and aggregation
#scala#collections
scalabeginner
Set Operations and Algorithms
Perform set operations: union, intersection, difference, subsets, and practical set algorithms.
Best for: Deduplication and uniqueness
#scala#set
scalaintermediate
Thread-Safe Concurrent Collections
Use concurrent collections for thread-safe access: TrieMap, concurrent queues, and synchronized wrappers.
Best for: Thread-safe service registries
#scala#concurrent