### Quick Start with OrderedMap v3 Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md A basic example demonstrating how to create, add, get, iterate, and delete elements in an OrderedMap. It shows how iteration maintains insertion order. ```go package main import ( "fmt" "github.com/elliotchance/orderedmap/v3" ) func main() { // Create m := orderedmap.NewOrderedMap[string, int]() // Add m.Set("apple", 1) m.Set("banana", 2) m.Set("cherry", 3) // Get if value, ok := m.Get("banana"); ok { fmt.Println(value) // 2 } // Iterate (maintains insertion order) for key, value := range m.AllFromFront() { fmt.Printf("%s: %d\n", key, value) } // Delete m.Delete("banana") // Size fmt.Println(m.Len()) // 2 } ``` -------------------------------- ### Install OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/MANIFEST.txt Install the latest version of the orderedmap package. Recommended for Go 1.23+. ```bash go get github.com/elliotchance/orderedmap/v3 ``` -------------------------------- ### Install OrderedMap v2 Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Use this command to install OrderedMap v2, compatible with Go 1.18-1.22. ```bash go get github.com/elliotchance/orderedmap/v2 ``` -------------------------------- ### OrderedMap Core Methods Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/MANIFEST.txt Illustrates common operations on an OrderedMap including setting, getting, deleting, and checking for existence. This example uses the v3 generic API. ```go package main import ( "fmt" "github.com/elliotchance/orderedmap/v3" ) func main() { om := orderedmap.NewOrderedMap[string, int]() om.Set("one", 1) om.Set("two", 2) om.Set("three", 3) // Get value val, ok := om.Get("two") if ok { fmt.Printf("Get 'two': %d\n", val) } // Check existence if om.Has("one") { fmt.Println("Map has 'one'") } // Delete element om.Delete("two") if !om.Has("two") { fmt.Println("Map no longer has 'two'") } // Get length fmt.Printf("Map length: %d\n", om.Len()) } ``` -------------------------------- ### Check for Key Existence and Get Value Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Use the `Get` method with the `ok` idiom to safely check if a key exists and retrieve its value. This pattern is useful for avoiding errors when a key might be absent. ```go if value, ok := m.Get("key"); ok { // Use value } else { // Key not found } ``` -------------------------------- ### Install OrderedMap v1 Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Use this command to install the older version of OrderedMap, for Go 1.12 and earlier. ```bash go get github.com/elliotchance/orderedmap ``` -------------------------------- ### Manual Iteration Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Provides examples for manual iteration using Front/Back and Next/Prev methods, suitable for Go versions prior to 1.23. ```APIDOC ## Manual Iteration Examples ### Description Demonstrates how to manually iterate over the ordered map elements using `Front()`, `Back()`, `Next()`, and `Prev()` methods. ### Forward Iteration ```go // Forward iteration for el := m.Front(); el != nil; el = el.Next() { fmt.Printf("%v: %v\n", el.Key, el.Value) } ``` ### Reverse Iteration ```go // Reverse iteration for el := m.Back(); el != nil; el = el.Prev() { fmt.Printf("%v: %v\n", el.Key, el.Value) } ``` ``` -------------------------------- ### Basic OrderedMap Usage Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/MANIFEST.txt Demonstrates creating an OrderedMap, adding elements, and retrieving values by key. This example uses the v3 generic API. ```go package main import ( "fmt" "github.com/elliotchance/orderedmap/v3" ) func main() { // Create a new ordered map with string keys and int values. om := orderedmap.NewOrderedMap[string, int]() // Add elements. The order is preserved. om.Set("apple", 1) om.Set("banana", 2) om.Set("cherry", 3) // Get a value by key. value, ok := om.Get("banana") if ok { fmt.Printf("Value for 'banana': %d\n", value) } // Iterate over the map in insertion order. fmt.Println("Iterating over map:") for pair := range om.Pairs() { fmt.Printf(" %s: %d\n", pair.Key, pair.Value) } } ``` -------------------------------- ### Get Value or Default (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Retrieve the value for a key, or return a provided default value if the key is not found. ```go GetOrDefault(key K, default V) V ``` -------------------------------- ### Iterate All From Front (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Returns an iterator sequence yielding key-value pairs starting from the front of the map. ```go AllFromFront() iter.Seq2[K, V] ``` -------------------------------- ### Iterate OrderedMap (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Examples of iterating through an ordered map in v3 using different approaches: forward, backward, keys only, and values only. ```go // Forward iteration for key, value := range m.AllFromFront() { } ``` ```go // Backward iteration for key, value := range m.AllFromBack() { } ``` ```go // Keys only for key := range m.Keys() { } ``` ```go // Values only for value := range m.Values() { } ``` -------------------------------- ### v3 Core Methods Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md These are the fundamental methods for interacting with the OrderedMap, including setting, getting, deleting, and checking for keys. ```APIDOC ## Core Methods (v3) ### `Set(key K, value V) bool` Sets the value for a given key. Returns true if the key was new, false if it existed and was updated. ### `Get(key K) (V, bool)` Retrieves the value associated with a key. Returns the value and true if the key exists, otherwise returns the zero value for V and false. ### `GetOrDefault(key K, default V) V` Retrieves the value for a key, returning a provided default value if the key does not exist. ### `GetElement(key K) *Element[K, V]` Retrieves a pointer to the Element associated with the key, allowing access to adjacent elements. ### `Delete(key K) bool` Deletes a key-value pair from the map. Returns true if the key was found and deleted, false otherwise. ### `Has(key K) bool` Checks if a key exists in the map. ### `Len() int` Returns the number of elements in the map. ### `Copy() *OrderedMap[K, V]` Creates a shallow copy of the ordered map. ### `ReplaceKey(originalKey K, newKey K) bool` Replaces an existing key with a new key, preserving the value and order. Returns true if successful, false if the original key does not exist. ``` -------------------------------- ### Get First Element (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Retrieve a pointer to the first Element in the ordered map. ```go Front() *Element[K, V] ``` -------------------------------- ### Iterate All From Back (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Returns an iterator sequence yielding key-value pairs starting from the back of the map. ```go AllFromBack() iter.Seq2[K, V] ``` -------------------------------- ### Get Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Retrieves the value for a given key. ```APIDOC ## Get ### Description Retrieves the value for a given key. ### Method Signature ```go func (m *OrderedMap[K, V]) Get(key K) (value V, ok bool) ``` ### Parameters #### Path Parameters - **key** (K) - Required - The key to retrieve ### Returns - **(V, bool)** - value and existence flag ### Example ```go value, ok := m.Get("foo") ``` ``` -------------------------------- ### Synchronized Concurrent Access Example Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/version-guide.md Demonstrates how to safely access an OrderedMap from multiple goroutines using a sync.RWMutex for synchronization. This is necessary as the OrderedMap itself is not designed for concurrent use. ```go var mu sync.RWMutex m := orderedmap.NewOrderedMap[string, int]() // Writing mu.Lock() m.Set("key", 42) mu.Unlock() // Reading mu.RLock() val, ok := m.Get("key") mu.RUnlock() ``` -------------------------------- ### Query Values from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/patterns.md Shows how to retrieve values by key, check for key existence, get a value with a default if the key is not found, and determine the map's size. Requires the 'fmt' package for printing. ```go // Get with existence check value, ok := m.Get("beta") if ok { fmt.Println(value) // 2 } // Get with default value := m.GetOrDefault("missing", -1) // -1 // Check existence if m.Has("alpha") { fmt.Println("Found") } // Get size fmt.Println(m.Len()) // 3 ``` -------------------------------- ### Get Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Retrieves the value for a given key. Returns the value and a boolean indicating whether the key exists. ```APIDOC ## Get ### Description Retrieves the value for a given key. Returns the value and a boolean indicating whether the key exists. ### Method Signature ```go func (m *OrderedMap[K, V]) Get(key K) (value V, ok bool) ``` ### Parameters #### Path Parameters - **key** (K) - Required - The key to retrieve ### Returns - **(V, bool)** - value and a boolean; boolean is true if the key exists, false otherwise ### Example ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("foo", 42) value, ok := m.Get("foo") // value = 42, ok = true value, ok = m.Get("missing") // value = 0, ok = false ``` ``` -------------------------------- ### Get Value by Key (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Retrieve the value associated with a key and a boolean indicating if the key was found. ```go Get(key K) (V, bool) ``` -------------------------------- ### OrderedMap Iteration Patterns Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/MANIFEST.txt Demonstrates different ways to iterate over an OrderedMap, including forward, reverse, and collecting elements. This example uses the v3 generic API. ```go package main import ( "fmt" "github.com/elliotchance/orderedmap/v3" ) func main() { om := orderedmap.NewOrderedMap[string, int]() om.Set("first", 1) om.Set("second", 2) om.Set("third", 3) // Forward iteration using Pairs() fmt.Println("Forward iteration:") for pair := range om.Pairs() { fmt.Printf(" %s: %d\n", pair.Key, pair.Value) } // Reverse iteration using ReversePairs() fmt.Println("Reverse iteration:") for pair := range om.ReversePairs() { fmt.Printf(" %s: %d\n", pair.Key, pair.Value) } // Collect keys into a slice keys := om.Keys() fmt.Printf("Keys: %v\n", keys) // Collect values into a slice values := om.Values() fmt.Printf("Values: %v\n", values) } ``` -------------------------------- ### Iterate and Collect Keys Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Use `Keys` to get an iterator for all keys in insertion order. You can iterate directly or use `slices.Collect` to gather all keys into a slice. ```go import "slices" m := orderedmap.NewOrderedMap[string, int]() m.Set("a", 1) m.Set("b", 2) for key := range m.Keys() { fmt.Println(key) } // Or collect into a slice keys := slices.Collect(m.Keys()) fmt.Println(keys) // [a b] ``` -------------------------------- ### Iterating Key-Value Pairs with Seq2 (v3 and v2) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/types.md Example of iterating over key-value pairs yielded by OrderedMap methods like AllFromFront() using the Seq2 iterator type. This shows consumption in a for-range loop and collection into a map. ```go for key, value := range m.AllFromFront() { fmt.Println(key, value) } mm := maps.Collect(m.AllFromFront()) ``` -------------------------------- ### Get Element by Key (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Retrieve the Element pointer associated with a key. Returns nil if the key is not found. ```go GetElement(key K) *Element[K, V] ``` -------------------------------- ### Iterating Keys with Seq (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/types.md Example of iterating over keys yielded by OrderedMap.Keys() using the Seq iterator type. This demonstrates how to consume the iterator in a standard Go for-range loop and collect results. ```go for key := range m.Keys() { fmt.Println(key) } keys := slices.Collect(m.Keys()) ``` -------------------------------- ### Iterate All Key-Value Pairs Front to Back Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Use `AllFromFront` to get an iterator for key-value pairs in insertion order. This is useful for processing elements from oldest to newest. Requires Go 1.23+. ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("a", 1) m.Set("b", 2) m.Set("c", 3) for key, value := range m.AllFromFront() { fmt.Printf("%s: %d\n", key, value) // Output: // a: 1 // b: 2 // c: 3 } ``` -------------------------------- ### JSON Parsing with Order Preservation using v3 OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/comparison.md Example of parsing JSON and preserving key order using the v3 ordered map, suitable for Go 1.23+. ```go m := orderedmap.NewOrderedMap[string, interface{}]() // Parse JSON and populate for key, value := range m.AllFromFront() { fmt.Printf("%s: %v\n", key, value) } ``` -------------------------------- ### OrderedMap Get Operation Data Flow Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/architecture.md Illustrates the steps involved in retrieving a value from the OrderedMap using its key. It highlights the O(1) time complexity for lookups. ```text OrderedMap.Get("key") │ └─ Look up "key" in kv map (O(1)) ├─ Found: return Element.Value and true └─ Not found: return zero value and false Result: O(1) lookup time ``` -------------------------------- ### Get Value with a Default Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Retrieve a value using `GetOrDefault`, providing a default value to be returned if the key is not found. This simplifies handling missing keys. ```go value := m.GetOrDefault("key", defaultValue) ``` -------------------------------- ### Iterate All Key-Value Pairs Back to Front Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Use `AllFromBack` to get an iterator for key-value pairs in reverse insertion order. This is useful for processing elements from newest to oldest. Requires Go 1.23+. ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("a", 1) m.Set("b", 2) m.Set("c", 3) for key, value := range m.AllFromBack() { fmt.Printf("%s: %d\n", key, value) // Output: // c: 3 // b: 2 // a: 1 } ``` -------------------------------- ### OrderedMap Basic Operations Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Covers fundamental operations like setting and getting values, checking for existence, deleting keys, and retrieving the map's size. The Set method indicates if a new key was added or an existing one replaced. ```go // Set/Get m.Set(key, value) // Returns true if new, false if replaced value, ok := m.Get(key) // Returns (value, exists) value := m.GetOrDefault(key, default) // Check/Delete exists := m.Has(key) deleted := m.Delete(key) // Returns true if key existed // Size length := m.Len() // Copy m2 := m.Copy() ``` -------------------------------- ### Configuration Management with OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/comparison.md Shows how to use an ordered map for configuration management, loading settings with specific order and allowing frequent lookups. ```go config := orderedmap.NewOrderedMap[string, string]() // Load from file preserving order for _, line := range configLines { key, value := parseConfigLine(line) config.Set(key, value) } // Fast lookup if setting, ok := config.Get("timeout"); ok { timeout := parseDuration(setting) } // Maintain order for writing back for key, value := range config.AllFromFront() { writeConfigLine(fmt.Sprintf("%s=%s", key, value)) } ``` -------------------------------- ### OrderedMap with Different Types (v2) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/MANIFEST.txt Example of using OrderedMap with generic types in Go versions 1.18-1.22. Note the use of `orderedmap.NewOrderedMap` which is available in v2 and v3. ```go package main import ( "fmt" "github.com/elliotchance/orderedmap/v2" ) func main() { // Create a map with int keys and string values. om := orderedmap.NewOrderedMap[int, string]() om.Set(10, "ten") om.Set(20, "twenty") om.Set(30, "thirty") // Iterate and print. for pair := range om.Pairs() { fmt.Printf("%d: %s\n", pair.Key, pair.Value) } } ``` -------------------------------- ### Initialize and Populate OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/patterns.md Demonstrates how to create an empty OrderedMap or one with a pre-allocated capacity, and how to set initial values. Insertion order is preserved. ```go import "github.com/elliotchance/orderedmap/v3" // Create empty map m := orderedmap.NewOrderedMap[string, int]() // Create with pre-allocated capacity m := orderedmap.NewOrderedMapWithCapacity[string, int](100) // Set values (insertion order is preserved) m.Set("alpha", 1) m.Set("beta", 2) m.Set("gamma", 3) ``` -------------------------------- ### OrderedMap Creation Methods Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Demonstrates different ways to create an OrderedMap, including a standard constructor and one that specifies initial capacity. ```go // v3 example m := orderedmap.NewOrderedMap[string, int]() m := orderedmap.NewOrderedMapWithCapacity[string, int](100) ``` -------------------------------- ### State Machine Transition History with OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/comparison.md Illustrates tracking state transitions in order and querying by key using an ordered map. ```go history := orderedmap.NewOrderedMap[string, TransitionEvent]() // Add transition history.Set(timestamp, event) // Query specific transition if transition, ok := history.Get(queryTimestamp); ok { fmt.Printf("Transition: %v\n", transition) } // Replay all transitions in order for _, event := range slices.Collect(history.Values()) { replayTransition(event) } ``` -------------------------------- ### Get length of OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Returns the number of key-value pairs currently in the map. ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("a", 1) m.Set("b", 2) fmt.Println(m.Len()) // 2 ``` -------------------------------- ### Migration: v2 to v3 - Using iter.Seq Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/version-guide.md Illustrates migrating from v2 to v3 by updating imports and adopting the `iter.Seq` pattern for iteration. This provides a more idiomatic Go way to iterate over map elements. ```go // v2 import "github.com/elliotchance/orderedmap/v2" for el := m.Front(); el != nil; el = el.Next() { fmt.Println(el.Key, el.Value) } // v3 - use iter.Seq directly import "github.com/elliotchance/orderedmap/v3" for key, value := range m.AllFromFront() { fmt.Println(key, value) } ``` -------------------------------- ### Get Last Element (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Retrieve a pointer to the last Element in the ordered map. ```go Back() *Element[K, V] ``` -------------------------------- ### Basic OrderedMap Usage Source: https://github.com/elliotchance/orderedmap/blob/master/README.md Demonstrates how to create, set, and delete elements in an ordered map. Requires Go v1.23 or later. ```go import "github.com/elliotchance/orderedmap/v3" func main() { m := orderedmap.NewOrderedMap[string, any]() m.Set("foo", "bar") m.Set("qux", 1.23) m.Set("123", true) m.Delete("qux") } ``` -------------------------------- ### Get Map Length (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Return the number of key-value pairs currently in the ordered map. ```go Len() int ``` -------------------------------- ### v2: Manual Traversal and Key Slice (Go 1.18-1.22) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/version-guide.md Illustrates using the v2 OrderedMap for Go versions 1.18-1.22, showing manual linked list traversal using `Front()` and `Next()`, and retrieving all keys as a slice with `Keys()`. ```go import "github.com/elliotchance/orderedmap/v2" import "fmt" m := orderedmap.NewOrderedMap[string, int]() m.Set("foo", 42) // Manual linked list traversal for el := m.Front(); el != nil; el = el.Next() { fmt.Printf("%s: %d\n", el.Key, el.Value) } // Keys as slice keys := m.Keys() ``` -------------------------------- ### Basic OrderedMap Usage in Go Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Demonstrates creating an ordered map, adding elements, iterating in insertion order, and performing fast lookups. Requires Go 1.23+ for v3. ```go package main import ( "fmt" "github.com/elliotchance/orderedmap/v3" ) func main() { m := orderedmap.NewOrderedMap[string, int]() m.Set("alice", 1) m.Set("bob", 2) m.Set("charlie", 3) // Iterate in insertion order for key, value := range m.AllFromFront() { fmt.Printf("%s: %d\n", key, value) } // Output: alice: 1, bob: 2, charlie: 3 // Fast O(1) lookup if val, ok := m.Get("bob"); ok { fmt.Println(val) // 2 } } ``` -------------------------------- ### Get Size of OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Returns the total number of key-value pairs currently stored in the map. ```go fmt.Println(m.Len()) ``` -------------------------------- ### Iterate Forward and Backward Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Use `AllFromFront` and `AllFromBack` for forward and backward iteration over key-value pairs. These methods are specific to v3 of the library. ```go // Forward for key, value := range m.AllFromFront() { fmt.Println(key, value) } ``` ```go // Backward for key, value := range m.AllFromBack() { fmt.Println(key, value) } ``` -------------------------------- ### v1 OrderedMap Initialization and Usage (Non-generic) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/comparison.md Demonstrates how to create and use a non-generic ordered map in v1. Requires type assertions for retrieved values. ```go m := orderedmap.NewOrderedMap() m.Set("key", 42) value, _ := m.Get("key") intValue := value.(int) // Type assertion required ``` -------------------------------- ### Create a Copy (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Return a shallow copy of the ordered map. ```go Copy() *OrderedMap[K, V] ``` -------------------------------- ### v2 OrderedMap Initialization and Usage (Generic) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/comparison.md Shows how to create and use a generic ordered map in v2. Type safety is enforced, and type assertions are not needed for retrieved values. ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("key", 42) value, _ := m.Get("key") // value is already int ``` -------------------------------- ### Get Keys from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v1.md Retrieves all keys from the OrderedMap in their insertion order. Replaced keys maintain their original position. ```go m := orderedmap.NewOrderedMap() m.Set("first", 1) m.Set("second", 2) m.Set("third", 3) keys := m.Keys() fmt.Println(keys) // [first second third] ``` -------------------------------- ### Verify insertion order Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/patterns.md This snippet demonstrates how to verify that elements are stored and retrieved in the order they were inserted. It collects keys and compares them against an expected sequence. ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("z", 1) m.Set("a", 2) m.Set("m", 3) keys := slices.Collect(m.Keys()) expected := []string{"z", "a", "m"} if slices.Equal(keys, expected) { fmt.Println("Order preserved correctly") } ``` -------------------------------- ### Get Previous Element (Element Methods) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Move the iterator to the previous element and return it. Used with Element pointers. ```go Prev() *Element[K, V] ``` -------------------------------- ### Migration: v1 to v2 - Adding Type Parameters Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/version-guide.md Shows how to migrate from v1 to v2 by replacing imports and adding type parameters for type safety. This eliminates the need for type assertions when retrieving values. ```go // v1 import "github.com/elliotchance/orderedmap" m := orderedmap.NewOrderedMap() value, ok := m.Get("key") intValue := value.(int) // v2 import "github.com/elliotchance/orderedmap/v2" m := orderedmap.NewOrderedMap[string, int]() value, ok := m.Get("key") // value is already int, no casting needed ``` -------------------------------- ### Get Next Element (Element Methods) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Advance the iterator to the next element and return it. Used with Element pointers. ```go Next() *Element[K, V] ``` -------------------------------- ### LRU Cache Implementation with OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/comparison.md Demonstrates using an ordered map to implement an LRU cache, providing fast lookups and tracking insertion/access order. ```go cache := orderedmap.NewOrderedMap[string, CacheEntry]() // Add entry cache.Set(key, entry) // Look up is O(1) if value, ok := cache.Get(key); ok { // Use cached value } // Remove oldest if over capacity if cache.Len() > maxSize { oldest := cache.Front() cache.Delete(oldest.Key) } ``` -------------------------------- ### Get All Keys from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Returns a slice containing all keys in the map, ordered from oldest to newest based on insertion. ```go keys := m.Keys() ``` -------------------------------- ### Get Value from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Retrieves the value associated with a key. Returns the value and a boolean indicating if the key was found. ```go value, ok := m.Get("foo") ``` -------------------------------- ### Manual Traversal Forward and Backward Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Perform manual traversal using `Front()`, `Next()`, `Back()`, and `Prev()` methods. This approach is compatible with all versions of the library. ```go // Forward for el := m.Front(); el != nil; el = el.Next() { fmt.Println(el.Key, el.Value) } ``` ```go // Backward for el := m.Back(); el != nil; el = el.Prev() { fmt.Println(el.Key, el.Value) } ``` -------------------------------- ### Get Last Element from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Retrieves a pointer to the last (newest) element in the map. Returns nil if the map is empty. ```go last := m.Back() ``` -------------------------------- ### Get First Element from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Retrieves a pointer to the first (oldest) element in the map. Returns nil if the map is empty. ```go first := m.Front() ``` -------------------------------- ### Get Value or Default from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Retrieves the value for a key, or returns a specified default value if the key is not found in the map. ```go value := m.GetOrDefault("foo", 0) ``` -------------------------------- ### Create OrderedMap with Capacity (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Initialize an ordered map with a specified initial capacity for performance. For Go 1.23+. ```go NewOrderedMapWithCapacity[K, V](capacity int) *OrderedMap[K, V] ``` -------------------------------- ### Get value or default from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Retrieves the value for a given key. If the key does not exist, returns the provided default value instead. ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("foo", 42) value := m.GetOrDefault("foo", 0) // value = 42 value = m.GetOrDefault("missing", 99) // value = 99 ``` -------------------------------- ### v3 OrderedMap Initialization and Iteration (Generic with Iterators) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/comparison.md Illustrates using a generic ordered map in v3 with Go 1.23+ iterators for cleaner iteration. Supports native range loops. ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("key", 42) for key, value := range m.AllFromFront() { fmt.Println(key, value) // Cleaner iteration } ``` -------------------------------- ### Import OrderedMap v1 (Go 1.12 and earlier) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Use this import for Go 1.12 and earlier versions. ```go // v1 (Go 1.12 and earlier) import "github.com/elliotchance/orderedmap" ``` -------------------------------- ### Get Previous Element in Linked List Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v1.md Retrieves the preceding Element in the linked list. Returns nil if the current Element is the first one. ```go func (e *Element) Prev() *Element ``` -------------------------------- ### Get Next Element in Linked List Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v1.md Retrieves the subsequent Element in the linked list. Returns nil if the current Element is the last one. ```go func (e *Element) Next() *Element ``` -------------------------------- ### v3: Iterate and Collect with OrderedMap (Go 1.23+) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/version-guide.md Demonstrates using the v3 OrderedMap with Go 1.23+ features, including direct range iteration over key-value pairs and collecting keys into a slice using `slices.Collect()`. ```go import "github.com/elliotchance/orderedmap/v3" import "fmt" import "slices" m := orderedmap.NewOrderedMap[string, int]() m.Set("foo", 42) // Direct range iteration for key, value := range m.AllFromFront() { fmt.Printf("%s: %d\n", key, value) } // Collect into a slice keys := slices.Collect(m.Keys()) ``` -------------------------------- ### Get Reverse Iterator Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Provides an iterator for traversing key-value pairs from the back to the front of the ordered map. Requires Go 1.23 or later. ```go func (m *OrderedMap[K, V]) ReverseIterator() iter.Seq2[K, V] ``` -------------------------------- ### Get Forward Iterator Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Provides an iterator for traversing key-value pairs from the front to the back of the ordered map. Requires Go 1.23 or later. ```go func (m *OrderedMap[K, V]) Iterator() iter.Seq2[K, V] ``` -------------------------------- ### Concurrent Write and Read Synchronization Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v1.md Demonstrates how to use a sync.RWMutex for external synchronization to safely perform writes and reads on an OrderedMap in concurrent scenarios. Ensure writes are protected by Lock() and reads by RLock(). ```go var mu sync.RWMutex m := orderedmap.NewOrderedMap() // Writing mu.Lock() m.Set("key", "value") mu.Unlock() // Reading mu.RLock() value, ok := m.Get("key") mu.RUnlock() ``` -------------------------------- ### AllFromFront Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Returns an iterator that yields key-value pairs in insertion order (front to back). Requires Go 1.23+. ```APIDOC ## AllFromFront ### Description Returns an iterator that yields key-value pairs in insertion order (front to back). ### Method Signature ```go func (m *OrderedMap[K, V]) AllFromFront() iter.Seq2[K, V] ``` ### Returns `iter.Seq2[K, V]` - an iterator that yields (key, value) pairs from oldest to newest. ### Example ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("a", 1) m.Set("b", 2) m.Set("c", 3) for key, value := range m.AllFromFront() { fmt.Printf("%s: %d\n", key, value) // Output: // a: 1 // b: 2 // c: 3 } ``` ``` -------------------------------- ### Iterate and Collect Values Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Use `Values` to get an iterator for all values in insertion order. You can iterate directly or use `slices.Collect` to gather all values into a slice. ```go import "slices" m := orderedmap.NewOrderedMap[string, int]() m.Set("a", 1) m.Set("b", 2) for value := range m.Values() { fmt.Println(value) } // Or collect into a slice values := slices.Collect(m.Values()) fmt.Println(values) // [1 2] ``` -------------------------------- ### Import OrderedMap v3 (Go 1.23+) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Use this import for Go 1.23 and later versions. ```go // v3 (Go 1.23+) import "github.com/elliotchance/orderedmap/v3" ``` -------------------------------- ### Import Path for v1 Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/exported-symbols.md Use this import path for the v1 version of the orderedmap package. This is the original version of the library. ```go import "github.com/elliotchance/orderedmap" ``` -------------------------------- ### Thread-Safe Reading from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Perform read operations (Get) on an OrderedMap concurrently using a sync.RWMutex for read locking. Use RLock for concurrent reads. ```go var mu sync.RWMutex m := orderedmap.NewOrderedMap[string, int]() // Reading mu.RLock() val, ok := m.Get("key") mu.RUnlock() ``` -------------------------------- ### Check and Get Value from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Safely retrieve a value associated with a key, checking for its existence first. This pattern avoids panics if the key is not present. ```go if value, ok := m.Get(key); ok { use(value) } ``` -------------------------------- ### Create Map with Basic Type Parameters Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Instantiate an ordered map with specific key and value types using `NewOrderedMap`. Common types like strings, integers, and pointers are supported. ```go // String keys, int values m := orderedmap.NewOrderedMap[string, int]() // Int keys, string values m := orderedmap.NewOrderedMap[int, string]() // Pointer keys m := orderedmap.NewOrderedMap[*MyStruct, bool]() // Interface value (like v1) m := orderedmap.NewOrderedMap[string, interface{}()] ``` -------------------------------- ### Get Previous Element Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Retrieves the preceding element in the ordered map's linked list. Returns nil if the current element is the first one. ```go prev := el.Prev() ``` -------------------------------- ### Import OrderedMap v2 (Go 1.18-1.22) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Use this import for Go versions 1.18 through 1.22. ```go // v2 (Go 1.18-1.22) import "github.com/elliotchance/orderedmap/v2" ``` -------------------------------- ### Get Next Element Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Retrieves the subsequent element in the ordered map's linked list. Returns nil if the current element is the last one. ```go next := el.Next() ``` -------------------------------- ### v1 Usage: Manual Traversal and Key Retrieval Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/version-guide.md Demonstrates manual linked list traversal and key retrieval using type assertions in v1. Use this for Go versions prior to 1.18 where generics are not available. Note the required type casting for keys and values. ```go import "github.com/elliotchance/orderedmap" m := orderedmap.NewOrderedMap() m.Set("foo", 42) // Manual linked list traversal for el := m.Front(); el != nil; el = el.Next() { key := el.Key.(string) value := el.Value.(int) fmt.Printf("%s: %d\n", key, value) } // Keys as interface{} slice keys := m.Keys() ``` -------------------------------- ### Manual Iteration From Back Source: https://github.com/elliotchance/orderedmap/blob/master/README.md Manually iterates through the ordered map elements from back to front using Back() and Prev(). ```go // You can also use Back and Prev to iterate in reverse: for el := m.Back(); el != nil; el = el.Prev() { fmt.Println(el.Key, el.Value) } ``` -------------------------------- ### OrderedMap Navigation Methods Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/quick-reference.md Provides methods for navigating the map, including accessing the first and last elements, retrieving an element by key, and replacing a key while preserving its position. ```go // First and last first := m.Front() // Returns *Element or nil last := m.Back() // Returns *Element or nil // From key el := m.GetElement(key) // Returns *Element for key // Replace key (preserves position) success := m.ReplaceKey(oldKey, newKey) ``` -------------------------------- ### Get Element from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Returns the Element node for a given key, allowing direct access to the linked list element for traversal. Returns nil if the key does not exist. ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("foo", 42) el := m.GetElement("foo") if el != nil { fmt.Println(el.Value) // 42 nextEl := el.Next() } ``` -------------------------------- ### Create OrderedMap with Initial Elements Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Creates a new OrderedMap initialized with the provided elements. The elements are expected as a variadic slice of Element pointers. ```go func NewOrderedMapWithElements[K comparable, V any](els ...*Element[K, V]) *OrderedMap[K, V] ``` -------------------------------- ### Get Element Node from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v2.md Returns the internal Element node for a key, enabling direct access to linked list properties. Returns nil if the key is not found. ```go el := m.GetElement("foo") if el != nil { fmt.Println(el.Value) } ``` -------------------------------- ### Create OrderedMap with Initial Elements Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Use NewOrderedMapWithElements to create an OrderedMap initialized with provided elements. Elements are added in the order they are provided. ```go el1 := &orderedmap.Element[string, int]{Key: "a", Value: 1} el2 := &orderedmap.Element[string, int]{Key: "b", Value: 2} m := orderedmap.NewOrderedMapWithElements(el1, el2) ``` -------------------------------- ### Get Element by Key from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/element.md Use GetElement(key) to retrieve a specific element by its key. Returns nil if the key is not found. Access Key and Value properties directly. ```go el := m.GetElement("mykey") // Returns *Element[K, V], or nil if not found if el != nil { fmt.Println(el.Key, el.Value) } ``` -------------------------------- ### Manual Iteration From Front Source: https://github.com/elliotchance/orderedmap/blob/master/README.md Manually iterates through the ordered map elements from front to back using Front() and Next(). ```go // Iterate through all elements from oldest to newest: for el := m.Front(); el != nil; el = el.Next() { fmt.Println(el.Key, el.Value) } ``` -------------------------------- ### Get the First Element of OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v3.md Use Front to retrieve a pointer to the oldest element (first inserted) in the OrderedMap. Returns nil if the map is empty. This is useful for accessing the beginning of the ordered sequence. ```go m := orderedmap.NewOrderedMap[string, int]() m.Set("first", 1) m.Set("second", 2) first := m.Front() fmt.Println(first.Key) // "first" ``` -------------------------------- ### Create OrderedMap with Elements (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Construct an ordered map pre-populated with a slice of elements. For Go 1.23+. ```go NewOrderedMapWithElements[K, V](els ...*Element[K, V]) *OrderedMap[K, V] ``` -------------------------------- ### Get Element node by key in OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v1.md Returns the internal Element node for a given key, allowing direct access to the linked list element for traversal. Returns nil if the key does not exist. ```go m := orderedmap.NewOrderedMap() m.Set("foo", "bar") el := m.GetElement("foo") if el != nil { fmt.Println(el.Value) // "bar" nextEl := el.Next() // Get next element } ``` -------------------------------- ### Hash Map Component (Go map) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/architecture.md Stores key-to-Element pointers for fast lookups. Use the appropriate version based on your Go version. ```go kv map[K]*Element[K, V] // v2, v3 ``` ```go kv map[interface{}]*Element // v1 ``` -------------------------------- ### Check Key Existence (v3) Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/README.md Determine if a key exists in the ordered map. ```go Has(key K) bool ``` -------------------------------- ### Get value by key from OrderedMap Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/api-reference/orderedmap-v1.md Retrieves the value associated with a given key. Returns the value and a boolean indicating whether the key was found. If the key is not found, the value will be nil and the boolean will be false. ```go m := orderedmap.NewOrderedMap() m.Set("foo", "bar") value, ok := m.Get("foo") // value = "bar", ok = true value, ok = m.Get("missing") // value = nil, ok = false ``` -------------------------------- ### Constructor Functions Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/exported-symbols.md Functions to create new OrderedMap instances with different initialization options. ```APIDOC ## Constructor Functions ### `NewOrderedMap[K, V]()` / `NewOrderedMap()` Creates an empty OrderedMap with default capacity. ### `NewOrderedMapWithCapacity[K, V](capacity int)` / `NewOrderedMapWithCapacity(capacity int)` Creates an OrderedMap with a pre-allocated capacity. ### `NewOrderedMapWithElements[K, V](elements ...*Element)` (v2, v3 only) Creates an OrderedMap initialized with the provided elements. ``` -------------------------------- ### Import Path for v2 Source: https://github.com/elliotchance/orderedmap/blob/master/_autodocs/exported-symbols.md Use this import path to include the v2 version of the orderedmap package. This version introduced generic types and additional symbols compared to v1. ```go import "github.com/elliotchance/orderedmap/v2" ```