← Back to Scala Course | Chapter 6: Collections Basics | Lesson 6 of 8

Map क्या है

एक Map keys को values से जोड़ता है, जैसे एक phone book जहां एक नाम आपको एक number तक ले जाता है। आप एक key ढूंढते हैं और तुरंत उसकी value पा लेते हैं।

In this page:

  1. Map
Syntax
scala
val map = Map(key1 -> value1, key2 -> value2)
map(key)
map.get(key)
val updated = map + (key3 -> value3)

Map

एक Map key-value pairs store करता है और key के ज़रिए तेज़ lookup देता है, जिसे -> arrow syntax का उपयोग करते हुए Map("a" -> 1, "b" -> 2) से बनाया जाता है। Map(...) default रूप से immutable है, और keys unique होनी चाहिए।

map(key) से किसी गायब key को access करने पर throw होता है, इसलिए .get(key) (एक Option return करते हुए) या .getOrElse ज़्यादा सुरक्षित विकल्प हैं।

Warning: map(key) से किसी गायब key को access करने पर NoSuchElementException फेंकता है -- सुरक्षा के लिए .get(key) या .getOrElse(key, default) का उपयोग करें।

उदाहरण: Map

markup
object Main extends App {
  val ages = Map("Alice" -> 30, "Bob" -> 25)

  println(ages("Alice"))
  println(ages.getOrElse("Cara", -1))

  for ((name, age) <- ages) {
    println(s"$name is $age")
  }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी गायब key के लिए ages("Cara") का उपयोग करना, जो NoSuchElementException फेंकता है; getOrElse या get का उपयोग करें।
  2. colon के साथ Map("a": 1) लिखना, जबकि pairs -> उपयोग करते हैं।
  3. यह उम्मीद करना कि ages + ("Dan" -> 20) ages को modify करेगा, जबकि default Map immutable है और एक नया map return करता है।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.