AutolangDocs

Maps

A Map is a collection of key-value pairs where each key is unique. Maps are highly optimized for fast data retrieval, allowing you to look up a value instantly using its corresponding key.

Creating Maps

You can initialize a Map using the explicit constructor or via the intuitive syntactic sugar using curly braces. You must specify both the Key type and the Value type.

// 1. Explicit Constructor val explicitMap = Map<String, Int>() println("Is empty? ${if (explicitMap.isEmpty()) "Yes" else "No"}") // 2. Sugar Syntax val inventory = <String, Int>{"Apple": 10, "Banana": 20, "Cherry": 30} println("Size is: ${inventory.size()}") // Outputs: 3

Accessing & Modifying

Use set() to add new key-value pairs or update existing ones. Use get() to retrieve values. Note that get() returns an optional type (V?), which will evaluate to null if the key does not exist.

val m = <String, Int>{"Apple": 10} // Retrieve a value println(m.get("Apple")) // Outputs: 10 println(m.get("Durian")) // Outputs: null // Update an existing key m.set("Apple", 15) // Check if a key exists val hasCherry = m.containsKey("Cherry") // false // Remove a key-value pair m.remove("Apple") m.clear() // Empties the entire map

Iteration & Views

You can iterate over the Map using the forEach() method by passing a named callback function that takes both the key and the value. Additionally, you can extract all keys or all values into separate Autolang Arrays.

val numMap = <Int, Int>{1: 100, 2: 200, 3: 300} // Define a callback function func printEntry(key: Int, value: Int) { println("Key: ${key}, Value: ${value}") } // Iterate through the map numMap.forEach(printEntry) // Extract Keys and Values into Arrays val keysArr = numMap.keys() // [1, 2, 3] val valuesArr = numMap.values() // [100, 200, 300]

Methods Reference

Modification

  • set(key: K, value: V) - Inserts a new key-value pair or updates the value if the key already exists.
  • remove(key: K) - Removes the key and its corresponding value from the Map.
  • clear() - Removes all key-value pairs, resulting in an empty Map.

Querying

  • get(key: K): V? - Returns the value associated with the key, or null if the key does not exist.
  • getOrDefault(key: K, defaultValue: V): V - Returns the value associated with the key, or the provided default value if the key is not found.
  • containsKey(key: K): Bool - Returns true if the Map contains the specified key.
  • size(): Int - Returns the total number of key-value pairs in the Map.
  • isEmpty(): Bool - Returns true if the Map contains 0 items.

Iteration & Utility

  • forEach(fn: (K, V) -> Void) - Executes a callback function once for each key-value pair.
  • keys(): Array<K> - Returns a new Array containing all the keys in the Map.
  • values(): Array<V> - Returns a new Array containing all the values in the Map.
  • toString(): String - Returns a string representation of the Map.