Task

The goal is to create an associative array (also known as a dictionary, map, or hash).



Related tasks:

 Associative arrays/Iteration
 Hash from two arrays


See also

 Array
 Associative array: Creation, Iteration
 Collections
 Compound data type
 Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
 Linked list
 Queue: Definition, Usage
 Set
 Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
 Stack


// empty map
var emptyMap = new HashMap<String, Integer>()
 
// map initialization
var map = {"Scott"->50, "Carson"->40, "Luca"->30, "Kyle"->38}
 
// map key/value assignment
map["Scott"] = 51
 
// get a value
var x = map["Scott"]
 
// remove an entry
map.remove("Scott")
 
// loop and maps
for(entry in map.entrySet()) {
  print("Key: ${entry.Key}, Value: ${entry.Value}") 
}
 
// functional iteration
map.eachKey(\ k ->print(map[k]))
map.eachValue(\ v ->print(v))
map.eachKeyAndValue(\ k, v -> print("Key: ${v}, Value: ${v}"))
var filtered = map.filterByValues(\ v ->v < 50)
 
// any object can be treated as an associative array
class Person {
  var name: String
  var age: int 
}
// access properties on Person dynamically via associative array syntax
var scott = new Person()
scott["name"] = "Scott"
scott["age"] = 29