{"id":35570923,"url":"https://github.com/ilxqx/go-collections","last_synced_at":"2026-02-17T16:04:32.187Z","repository":{"id":332409185,"uuid":"1127770937","full_name":"ilxqx/go-collections","owner":"ilxqx","description":"Generic, fast, and ergonomic collections for Go 1.25+. Type-safe data structures with iter.Seq support.","archived":false,"fork":false,"pushed_at":"2026-01-05T13:02:09.000Z","size":224,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-01-13T19:45:51.352Z","etag":null,"topics":["btree","collections","data-structures","generics","go","golang","hashmap","hashset","iter-seq","type-safe"],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ilxqx.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-01-04T15:07:28.000Z","updated_at":"2026-01-05T13:02:11.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/ilxqx/go-collections","commit_stats":null,"previous_names":["ilxqx/go-collections"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/ilxqx/go-collections","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilxqx%2Fgo-collections","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilxqx%2Fgo-collections/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilxqx%2Fgo-collections/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilxqx%2Fgo-collections/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ilxqx","download_url":"https://codeload.github.com/ilxqx/go-collections/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilxqx%2Fgo-collections/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29549235,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-17T14:33:00.708Z","status":"ssl_error","status_checked_at":"2026-02-17T14:32:58.657Z","response_time":100,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["btree","collections","data-structures","generics","go","golang","hashmap","hashset","iter-seq","type-safe"],"created_at":"2026-01-04T17:14:34.873Z","updated_at":"2026-02-17T16:04:32.171Z","avatar_url":"https://github.com/ilxqx.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# go-collections\n\n[![Go Reference](https://pkg.go.dev/badge/github.com/ilxqx/go-collections.svg)](https://pkg.go.dev/github.com/ilxqx/go-collections)\n[![Go Report Card](https://goreportcard.com/badge/github.com/ilxqx/go-collections)](https://goreportcard.com/report/github.com/ilxqx/go-collections)\n[![Build Status](https://github.com/ilxqx/go-collections/actions/workflows/test.yml/badge.svg)](https://github.com/ilxqx/go-collections/actions/workflows/test.yml)\n[![codecov](https://codecov.io/gh/ilxqx/go-collections/branch/main/graph/badge.svg)](https://codecov.io/gh/ilxqx/go-collections)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)\n\nGeneric, fast, and ergonomic collections for Go 1.25+. This library provides a comprehensive set of type-safe, generic data structures with clean APIs, consistent naming, and support for Go's `iter.Seq`/`iter.Seq2` for seamless for-range integration.\n\n## Table of Contents\n\n- [Features](#features)\n- [Requirements](#requirements)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Constraints and Helpers](#constraints-and-helpers)\n- [Sets](#sets)\n  - [Set Interface](#set-interface)\n  - [SortedSet Interface](#sortedset-interface)\n  - [HashSet](#hashset)\n  - [TreeSet](#treeset)\n  - [ConcurrentHashSet](#concurrenthashset)\n  - [ConcurrentTreeSet](#concurrenttreeset)\n  - [ConcurrentSkipSet](#concurrentskipset)\n- [Maps](#maps)\n  - [Map Interface](#map-interface)\n  - [SortedMap Interface](#sortedmap-interface)\n  - [HashMap](#hashmap)\n  - [TreeMap](#treemap)\n  - [ConcurrentHashMap](#concurrenthashmap)\n  - [ConcurrentTreeMap](#concurrenttreemap)\n  - [ConcurrentSkipMap](#concurrentskipmap)\n- [Lists](#lists)\n  - [List Interface](#list-interface)\n  - [ArrayList](#arraylist)\n  - [LinkedList](#linkedlist)\n  - [Concurrent List Implementations](#concurrent-list-implementations)\n  - [Concurrent List Comparison](#concurrent-list-comparison)\n- [Stacks](#stacks)\n  - [Stack Interface](#stack-interface)\n  - [ArrayStack](#arraystack)\n- [Queues](#queues)\n  - [Queue Interface](#queue-interface)\n  - [ArrayQueue](#arrayqueue)\n  - [PriorityQueue](#priorityqueue)\n- [Deques](#deques)\n  - [Deque Interface](#deque-interface)\n  - [ArrayDeque](#arraydeque)\n- [License](#license)\n\n## Features\n\n- **Type-Safe Generics**: All collections are fully generic with compile-time type safety\n- **Type-Safe Generics**: All collections are fully generic with compile-time type safety\n- **Interface Segregation**: Small, focused interfaces composed into higher-level ones\n- **Go 1.25+ Iteration**: Native support for `iter.Seq` and `iter.Seq2` for seamless for-range loops\n- **Consistent API**: Uniform naming across Set/Map/List; `(value, ok)` return patterns\n- **Concurrent Variants**: Thread-safe collections with atomic operations\n- **No Reflection**: Zero runtime reflection for maximum performance\n- **Sorted Collections**: B-Tree and Skip List backed sorted sets and maps\n- **Memory Efficient**: Optimized to prevent memory leaks with `slices.Delete` and proper capacity management\n\n## Requirements\n\n- Go 1.25 or later (uses `iter.Seq`/`iter.Seq2`, `testing.B.Loop`, built-in `min`/`max`)\n\n## Installation\n\n```bash\ngo get github.com/ilxqx/go-collections\n```\n\n## Quick Start\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/ilxqx/go-collections\"\n)\n\nfunc main() {\n    // Create a HashSet\n    set := collections.NewHashSetFrom(1, 2, 3, 4, 5)\n\n    // Iterate using for-range with iter.Seq\n    for v := range set.Seq() {\n        fmt.Println(v)\n    }\n\n    // Set operations\n    other := collections.NewHashSetFrom(4, 5, 6, 7)\n    union := set.Union(other)\n    intersection := set.Intersection(other)\n\n    fmt.Printf(\"Union size: %d\\n\", union.Size())\n    fmt.Printf(\"Intersection size: %d\\n\", intersection.Size())\n\n    // Create a HashMap\n    m := collections.NewHashMap[string, int]()\n    m.Put(\"one\", 1)\n    m.Put(\"two\", 2)\n\n    if v, ok := m.Get(\"one\"); ok {\n        fmt.Printf(\"one = %d\\n\", v)\n    }\n\n    // Create a sorted TreeSet\n    sorted := collections.NewTreeSetOrdered[int]()\n    sorted.AddAll(5, 3, 1, 4, 2)\n\n    // Iterate in sorted order\n    for v := range sorted.Seq() {\n        fmt.Println(v) // 1, 2, 3, 4, 5\n    }\n}\n```\n\n## Constraints and Helpers\n\n### Type Constraints\n\n```go\n// Ordered is a constraint for types that support \u003c, ==, \u003e operators.\n// Aliases cmp.Ordered from the standard library.\ntype Ordered = cmp.Ordered\n\n// Comparator compares two values: negative if a \u003c b, zero if a == b, positive if a \u003e b.\ntype Comparator[T any] func(a, b T) int\n\n// Equaler reports whether two values are equal.\ntype Equaler[T any] func(a, b T) bool\n```\n\n### Helper Functions\n\n```go\n// EqualFunc returns a default Equaler for comparable types using ==.\nfunc EqualFunc[T comparable]() Equaler[T]\n\n// CompareFunc returns a Comparator for Ordered types using cmp.Compare.\nfunc CompareFunc[T Ordered]() Comparator[T]\n```\n\n**Usage:**\n\n```go\n// Using EqualFunc for list operations\nlist := collections.NewArrayListFrom(1, 2, 3, 2, 1)\nlist.Remove(2, collections.EqualFunc[int]())\n\n// Using CompareFunc for sorting\nlist.Sort(collections.CompareFunc[int]())\n```\n\n---\n\n## Sets\n\n### Set Interface\n\n`Set[T]` is an unordered collection of unique elements.\n\n| Method | Description |\n|--------|-------------|\n| `Size() int` | Returns the number of elements |\n| `IsEmpty() bool` | Reports whether the set is empty |\n| `Clear()` | Removes all elements |\n| `ToSlice() []T` | Returns a snapshot slice of all elements |\n| `String() string` | Returns a string representation |\n| `Seq() iter.Seq[T]` | Returns a sequence for for-range |\n| `ForEach(action func(T) bool)` | Iterates elements; stops if action returns false |\n| `Add(element T) bool` | Inserts element if absent; returns true if set changed |\n| `AddAll(elements ...T) int` | Inserts all elements; returns count added |\n| `AddSeq(seq iter.Seq[T]) int` | Inserts from sequence; returns count added |\n| `Remove(element T) bool` | Removes element; returns true if removed |\n| `RemoveAll(elements ...T) int` | Removes all elements; returns count removed |\n| `RemoveSeq(seq iter.Seq[T]) int` | Removes from sequence; returns count removed |\n| `RemoveFunc(predicate func(T) bool) int` | Removes elements satisfying predicate |\n| `RetainFunc(predicate func(T) bool) int` | Keeps only elements satisfying predicate |\n| `Pop() (T, bool)` | Removes and returns an arbitrary element |\n| `Contains(element T) bool` | Reports whether element exists |\n| `ContainsAll(elements ...T) bool` | Reports whether all elements exist |\n| `ContainsAny(elements ...T) bool` | Reports whether any element exists |\n| `Union(other Set[T]) Set[T]` | Returns s ∪ other |\n| `Intersection(other Set[T]) Set[T]` | Returns s ∩ other |\n| `Difference(other Set[T]) Set[T]` | Returns s - other |\n| `SymmetricDifference(other Set[T]) Set[T]` | Returns (s - other) ∪ (other - s) |\n| `IsSubsetOf(other Set[T]) bool` | Reports whether s ⊆ other |\n| `IsSupersetOf(other Set[T]) bool` | Reports whether s ⊇ other |\n| `IsProperSubsetOf(other Set[T]) bool` | Reports whether s ⊂ other |\n| `IsProperSupersetOf(other Set[T]) bool` | Reports whether s ⊃ other |\n| `IsDisjoint(other Set[T]) bool` | Reports whether s and other have no common elements |\n| `Equals(other Set[T]) bool` | Reports whether sets are equal |\n| `Clone() Set[T]` | Returns a shallow copy |\n| `Filter(predicate func(T) bool) Set[T]` | Returns new set with matching elements |\n| `Find(predicate func(T) bool) (T, bool)` | Returns first matching element |\n| `Any(predicate func(T) bool) bool` | Returns true if any element matches |\n| `Every(predicate func(T) bool) bool` | Returns true if all elements match |\n\n### SortedSet Interface\n\n`SortedSet[T]` extends `Set[T]` with sorted order operations.\n\n| Method | Description |\n|--------|-------------|\n| `First() (T, bool)` | Returns the smallest element |\n| `Last() (T, bool)` | Returns the largest element |\n| `Min() (T, bool)` | Alias for First |\n| `Max() (T, bool)` | Alias for Last |\n| `PopFirst() (T, bool)` | Removes and returns the smallest element |\n| `PopLast() (T, bool)` | Removes and returns the largest element |\n| `Floor(x T) (T, bool)` | Returns greatest element ≤ x |\n| `Ceiling(x T) (T, bool)` | Returns smallest element ≥ x |\n| `Lower(x T) (T, bool)` | Returns greatest element \u003c x |\n| `Higher(x T) (T, bool)` | Returns smallest element \u003e x |\n| `Range(from, to T, action func(T) bool)` | Iterates elements in [from, to] |\n| `RangeSeq(from, to T) iter.Seq[T]` | Returns sequence for [from, to] |\n| `Ascend(action func(T) bool)` | Iterates in ascending order |\n| `Descend(action func(T) bool)` | Iterates in descending order |\n| `AscendFrom(pivot T, action func(T) bool)` | Iterates elements ≥ pivot ascending |\n| `DescendFrom(pivot T, action func(T) bool)` | Iterates elements ≤ pivot descending |\n| `Reversed() iter.Seq[T]` | Returns descending sequence |\n| `SubSet(from, to T) SortedSet[T]` | Returns elements in [from, to] |\n| `HeadSet(to T, inclusive bool) SortedSet[T]` | Returns elements \u003c to (or ≤) |\n| `TailSet(from T, inclusive bool) SortedSet[T]` | Returns elements \u003e from (or ≥) |\n| `Rank(x T) int` | Returns 0-based rank; -1 if absent |\n| `GetByRank(rank int) (T, bool)` | Returns element at rank |\n| `CloneSorted() SortedSet[T]` | Returns shallow copy as SortedSet |\n\n### HashSet\n\nHash-based unordered set backed by `map[T]struct{}`.\n\n**Constructors:**\n\n```go\nfunc NewHashSet[T comparable]() Set[T]\nfunc NewHashSetWithCapacity[T comparable](capacity int) Set[T]\nfunc NewHashSetFrom[T comparable](elements ...T) Set[T]\n```\n\n**Example:**\n\n```go\nset := collections.NewHashSetFrom(\"apple\", \"banana\", \"cherry\")\n\nset.Add(\"date\")\nset.Remove(\"banana\")\n\nfor fruit := range set.Seq() {\n    fmt.Println(fruit)\n}\n\n// Set algebra\nother := collections.NewHashSetFrom(\"cherry\", \"date\", \"elderberry\")\nunion := set.Union(other)\nintersection := set.Intersection(other)\n```\n\n### TreeSet\n\nSorted set backed by B-Tree. Maintains elements in comparator order.\n\n**Constructors:**\n\n```go\nfunc NewTreeSet[T any](c Comparator[T]) SortedSet[T]\nfunc NewTreeSetOrdered[T Ordered]() SortedSet[T]\nfunc NewTreeSetFrom[T any](c Comparator[T], elements ...T) SortedSet[T]\n```\n\n**Example:**\n\n```go\n// For Ordered types (int, string, etc.)\nset := collections.NewTreeSetOrdered[int]()\nset.AddAll(5, 3, 1, 4, 2)\n\nfirst, _ := set.First()  // 1\nlast, _ := set.Last()    // 5\n\n// Range query\nset.Range(2, 4, func(v int) bool {\n    fmt.Println(v)  // 2, 3, 4\n    return true\n})\n\n// Custom comparator (reverse order)\nreverseSet := collections.NewTreeSet(func(a, b int) int {\n    return b - a  // Descending\n})\n```\n\n### ConcurrentHashSet\n\nThread-safe hash set backed by `xsync.MapOf`.\n\n**Constructors:**\n\n```go\nfunc NewConcurrentHashSet[T comparable]() ConcurrentSet[T]\nfunc NewConcurrentHashSetFrom[T comparable](elements ...T) ConcurrentSet[T]\n```\n\n**Additional Methods (ConcurrentSet):**\n\n| Method | Description |\n|--------|-------------|\n| `AddIfAbsent(element T) bool` | Atomically adds if absent |\n| `RemoveAndGet(element T) (T, bool)` | Atomically removes and returns |\n\n**Example:**\n\n```go\nset := collections.NewConcurrentHashSet[int]()\n\n// Safe for concurrent use\ngo func() { set.Add(1) }()\ngo func() { set.Add(2) }()\n\n// Atomic operations\nif set.AddIfAbsent(3) {\n    fmt.Println(\"3 was added\")\n}\n```\n\n### ConcurrentTreeSet\n\nThread-safe sorted set using RWMutex-protected TreeSet.\n\n**Constructors:**\n\n```go\nfunc NewConcurrentTreeSet[T any](cmpT Comparator[T]) ConcurrentSortedSet[T]\nfunc NewConcurrentTreeSetOrdered[T Ordered]() ConcurrentSortedSet[T]\nfunc NewConcurrentTreeSetFrom[T any](cmpT Comparator[T], elements ...T) ConcurrentSortedSet[T]\n```\n\n### ConcurrentSkipSet\n\nLock-free concurrent sorted set backed by skip list. For `Ordered` types only.\n\n**Constructors:**\n\n```go\nfunc NewConcurrentSkipSet[T Ordered]() ConcurrentSortedSet[T]\nfunc NewConcurrentSkipSetFrom[T Ordered](elements ...T) ConcurrentSortedSet[T]\n```\n\n---\n\n## Maps\n\n### Map Interface\n\n`Map[K, V]` is a collection that maps keys to values.\n\n| Method | Description |\n|--------|-------------|\n| `Size() int` | Returns the number of entries |\n| `IsEmpty() bool` | Reports whether the map is empty |\n| `Clear()` | Removes all entries |\n| `String() string` | Returns a string representation |\n| `Put(key K, value V) (V, bool)` | Associates value with key; returns (old, existed) |\n| `PutIfAbsent(key K, value V) (V, bool)` | Stores if absent; returns (value, inserted) |\n| `PutAll(other Map[K, V])` | Copies all entries from other |\n| `PutSeq(seq iter.Seq2[K, V]) int` | Copies from sequence; returns keys changed |\n| `Get(key K) (V, bool)` | Returns (value, exists) |\n| `GetOrDefault(key K, defaultValue V) V` | Returns value or default |\n| `Remove(key K) (V, bool)` | Removes key; returns (old, existed) |\n| `RemoveIf(key K, value V, eq Equaler[V]) bool` | Removes if value matches |\n| `ContainsKey(key K) bool` | Reports whether key exists |\n| `ContainsValue(value V, eq Equaler[V]) bool` | Reports whether value exists (O(n)) |\n| `RemoveKeys(keys ...K) int` | Removes keys; returns count |\n| `RemoveKeysSeq(seq iter.Seq[K]) int` | Removes from sequence |\n| `RemoveFunc(predicate func(K, V) bool) int` | Removes matching entries |\n| `Compute(key K, remapping func(K, V, bool) (V, bool)) (V, bool)` | Recomputes mapping |\n| `ComputeIfAbsent(key K, mapping func(K) V) V` | Computes if absent |\n| `ComputeIfPresent(key K, remapping func(K, V) (V, bool)) (V, bool)` | Recomputes if present |\n| `Merge(key K, value V, remapping func(V, V) (V, bool)) (V, bool)` | Merges with existing |\n| `Replace(key K, value V) (V, bool)` | Replaces if present |\n| `ReplaceIf(key K, old, new V, eq Equaler[V]) bool` | Replaces if value matches |\n| `ReplaceAll(function func(K, V) V)` | Replaces all values |\n| `Keys() []K` | Returns all keys |\n| `Values() []V` | Returns all values |\n| `Entries() []Entry[K, V]` | Returns all entries |\n| `ForEach(action func(K, V) bool)` | Iterates entries |\n| `Seq() iter.Seq2[K, V]` | Returns (key, value) sequence |\n| `SeqKeys() iter.Seq[K]` | Returns keys sequence |\n| `SeqValues() iter.Seq[V]` | Returns values sequence |\n| `Clone() Map[K, V]` | Returns shallow copy |\n| `Filter(predicate func(K, V) bool) Map[K, V]` | Returns filtered map |\n| `Equals(other Map[K, V], valueEq Equaler[V]) bool` | Reports equality |\n\n### SortedMap Interface\n\n`SortedMap[K, V]` extends `Map[K, V]` with sorted key operations.\n\n| Method | Description |\n|--------|-------------|\n| `FirstKey() (K, bool)` | Returns smallest key |\n| `LastKey() (K, bool)` | Returns largest key |\n| `FirstEntry() (Entry[K, V], bool)` | Returns entry with smallest key |\n| `LastEntry() (Entry[K, V], bool)` | Returns entry with largest key |\n| `PopFirst() (Entry[K, V], bool)` | Removes smallest-key entry |\n| `PopLast() (Entry[K, V], bool)` | Removes largest-key entry |\n| `FloorKey(k K) (K, bool)` | Returns greatest key ≤ k |\n| `CeilingKey(k K) (K, bool)` | Returns smallest key ≥ k |\n| `LowerKey(k K) (K, bool)` | Returns greatest key \u003c k |\n| `HigherKey(k K) (K, bool)` | Returns smallest key \u003e k |\n| `FloorEntry(k K) (Entry[K, V], bool)` | Returns entry with greatest key ≤ k |\n| `CeilingEntry(k K) (Entry[K, V], bool)` | Returns entry with smallest key ≥ k |\n| `LowerEntry(k K) (Entry[K, V], bool)` | Returns entry with greatest key \u003c k |\n| `HigherEntry(k K) (Entry[K, V], bool)` | Returns entry with smallest key \u003e k |\n| `Range(from, to K, action func(K, V) bool)` | Iterates [from, to] |\n| `RangeSeq(from, to K) iter.Seq2[K, V]` | Returns sequence for [from, to] |\n| `RangeFrom(from K, action func(K, V) bool)` | Iterates keys ≥ from |\n| `RangeTo(to K, action func(K, V) bool)` | Iterates keys ≤ to |\n| `Ascend(action func(K, V) bool)` | Iterates ascending |\n| `Descend(action func(K, V) bool)` | Iterates descending |\n| `AscendFrom(pivot K, action func(K, V) bool)` | Iterates ≥ pivot ascending |\n| `DescendFrom(pivot K, action func(K, V) bool)` | Iterates ≤ pivot descending |\n| `Reversed() iter.Seq2[K, V]` | Returns descending sequence |\n| `SubMap(from, to K) SortedMap[K, V]` | Returns entries in [from, to] |\n| `HeadMap(to K, inclusive bool) SortedMap[K, V]` | Returns entries \u003c to (or ≤) |\n| `TailMap(from K, inclusive bool) SortedMap[K, V]` | Returns entries \u003e from (or ≥) |\n| `RankOfKey(key K) int` | Returns 0-based rank; -1 if absent |\n| `GetByRank(rank int) (Entry[K, V], bool)` | Returns entry at rank |\n| `CloneSorted() SortedMap[K, V]` | Returns shallow copy as SortedMap |\n\n### Entry Type\n\n```go\ntype Entry[K, V any] struct {\n    Key   K\n    Value V\n}\n\n// Unpack returns the key and value for convenient destructuring.\nfunc (e Entry[K, V]) Unpack() (K, V)\n```\n\n### HashMap\n\nHash-based unordered map backed by `map[K]V`.\n\n**Constructors:**\n\n```go\nfunc NewHashMap[K comparable, V any]() Map[K, V]\nfunc NewHashMapWithCapacity[K comparable, V any](capacity int) Map[K, V]\nfunc NewHashMapFrom[K comparable, V any](src map[K]V) Map[K, V]\n```\n\n**Additional Interface:**\n\n```go\n**Example:**\n\n```go\nm := collections.NewHashMap[string, int]()\nm.Put(\"one\", 1)\nm.Put(\"two\", 2)\nm.Put(\"three\", 3)\n\n// Get with existence check\nif v, ok := m.Get(\"two\"); ok {\n    fmt.Printf(\"two = %d\\n\", v)\n}\n\n// Iterate\nfor k, v := range m.Seq() {\n    fmt.Printf(\"%s: %d\\n\", k, v)\n}\n\n// Compute operations\nm.ComputeIfAbsent(\"four\", func(k string) int {\n    return len(k)  // 4\n})\n```\n\n### TreeMap\n\nSorted map backed by B-Tree.\n\n**Constructors:**\n\n```go\nfunc NewTreeMap[K any, V any](cmpK Comparator[K]) SortedMap[K, V]\nfunc NewTreeMapOrdered[K Ordered, V any]() SortedMap[K, V]\nfunc NewTreeMapFrom[K comparable, V any](cmpK Comparator[K], m map[K]V) SortedMap[K, V]\n```\n\n**Example:**\n\n```go\nm := collections.NewTreeMapOrdered[int, string]()\nm.Put(3, \"three\")\nm.Put(1, \"one\")\nm.Put(2, \"two\")\n\n// Iterate in sorted key order\nfor k, v := range m.Seq() {\n    fmt.Printf(\"%d: %s\\n\", k, v)  // 1, 2, 3\n}\n\n// Navigation\nfloor, _ := m.FloorKey(2)      // 2\nceiling, _ := m.CeilingKey(2)  // 2\nlower, _ := m.LowerKey(2)      // 1\nhigher, _ := m.HigherKey(2)    // 3\n```\n\n### ConcurrentHashMap\n\nThread-safe hash map backed by `xsync.MapOf`.\n\n**Constructors:**\n\n```go\nfunc NewConcurrentHashMap[K comparable, V any]() ConcurrentMap[K, V]\nfunc NewConcurrentHashMapFrom[K comparable, V any](src map[K]V) ConcurrentMap[K, V]\n```\n\n**Additional Methods (ConcurrentMap):**\n\n| Method | Description |\n|--------|-------------|\n| `GetOrCompute(key K, compute func() V) (V, bool)` | Atomically get or compute |\n| `RemoveAndGet(key K) (V, bool)` | Atomically removes and returns |\n| `PutIfAbsent(key K, value V) (V, bool)` | Atomically stores if absent |\n| `CompareAndSwap(key K, old, new V, eq Equaler[V]) bool` | Atomic CAS |\n| `CompareAndDelete(key K, value V, eq Equaler[V]) bool` | Atomic compare-and-delete |\n\n**Example:**\n\n```go\nm := collections.NewConcurrentHashMap[string, int]()\n\n// Safe for concurrent use\nvar wg sync.WaitGroup\nfor i := 0; i \u003c 100; i++ {\n    wg.Add(1)\n    go func(n int) {\n        defer wg.Done()\n        m.Put(fmt.Sprintf(\"key%d\", n), n)\n    }(i)\n}\nwg.Wait()\n\n// Atomic operations\nv, computed := m.GetOrCompute(\"expensive\", func() int {\n    return expensiveCalculation()\n})\n```\n\n### ConcurrentTreeMap\n\nThread-safe sorted map using RWMutex-protected TreeMap.\n\n**Constructors:**\n\n```go\nfunc NewConcurrentTreeMap[K any, V any](cmpK Comparator[K]) ConcurrentSortedMap[K, V]\nfunc NewConcurrentTreeMapOrdered[K Ordered, V any]() ConcurrentSortedMap[K, V]\nfunc NewConcurrentTreeMapFrom[K comparable, V any](cmpK Comparator[K], m map[K]V) ConcurrentSortedMap[K, V]\n```\n\n### ConcurrentSkipMap\n\nLock-free concurrent sorted map backed by skip list. For `Ordered` keys only.\n\n**Atomicity Note:** Single-key operations (`Get`/`Put`/`PutIfAbsent`/`RemoveAndGet`) are atomic. However, `CompareAndSwap` and `CompareAndDelete` are **best-effort** under high contention due to the lock-free nature of skip lists. For strict CAS semantics, use `ConcurrentTreeMap` instead.\n\n**Constructors:**\n\n```go\nfunc NewConcurrentSkipMap[K Ordered, V any]() ConcurrentSortedMap[K, V]\nfunc NewConcurrentSkipMapFrom[K Ordered, V any](src map[K]V) ConcurrentSortedMap[K, V]\n```\n\n---\n\n## Lists\n\n### List Interface\n\n`List[T]` is an ordered collection with index-based access.\n\n| Method | Description |\n|--------|-------------|\n| `Size() int` | Returns the number of elements |\n| `IsEmpty() bool` | Reports whether the list is empty |\n| `Clear()` | Removes all elements |\n| `ToSlice() []T` | Returns a snapshot slice |\n| `String() string` | Returns a string representation |\n| `Seq() iter.Seq[T]` | Returns a sequence for for-range |\n| `ForEach(action func(T) bool)` | Iterates elements |\n| `Get(index int) (T, bool)` | Returns element at index |\n| `Set(index int, element T) (T, bool)` | Replaces element; returns old |\n| `First() (T, bool)` | Returns first element |\n| `Last() (T, bool)` | Returns last element |\n| `Add(element T)` | Appends element |\n| `AddAll(elements ...T)` | Appends all elements |\n| `AddSeq(seq iter.Seq[T])` | Appends from sequence |\n| `Insert(index int, element T) bool` | Inserts at index |\n| `InsertAll(index int, elements ...T) bool` | Inserts all at index |\n| `RemoveAt(index int) (T, bool)` | Removes at index |\n| `Remove(element T, eq Equaler[T]) bool` | Removes first occurrence |\n| `RemoveFirst() (T, bool)` | Removes first element |\n| `RemoveLast() (T, bool)` | Removes last element |\n| `RemoveFunc(predicate func(T) bool) int` | Removes matching elements |\n| `RetainFunc(predicate func(T) bool) int` | Keeps matching elements |\n| `IndexOf(element T, eq Equaler[T]) int` | Returns first index; -1 if absent |\n| `LastIndexOf(element T, eq Equaler[T]) int` | Returns last index; -1 if absent |\n| `Contains(element T, eq Equaler[T]) bool` | Reports whether element exists |\n| `Find(predicate func(T) bool) (T, bool)` | Returns first matching element |\n| `FindIndex(predicate func(T) bool) int` | Returns first matching index |\n| `SubList(from, to int) List[T]` | Returns elements in [from, to) |\n| `Reversed() iter.Seq[T]` | Returns reverse sequence |\n| `Clone() List[T]` | Returns shallow copy |\n| `Filter(predicate func(T) bool) List[T]` | Returns filtered list |\n| `Sort(cmp Comparator[T])` | Sorts in place |\n| `Any(predicate func(T) bool) bool` | Returns true if any match |\n| `Every(predicate func(T) bool) bool` | Returns true if all match |\n\n### ArrayList\n\nDynamic array-backed list with O(1) append and O(n) insert/remove.\n\n**Constructors:**\n\n```go\nfunc NewArrayList[T any]() List[T]\nfunc NewArrayListWithCapacity[T any](capacity int) List[T]\nfunc NewArrayListFrom[T any](elements ...T) List[T]\n```\n\n**Example:**\n\n```go\nlist := collections.NewArrayListFrom(1, 2, 3)\n\nlist.Add(4)\nlist.Insert(0, 0)  // [0, 1, 2, 3, 4]\n\nv, _ := list.Get(2)  // 2\nlist.Set(2, 20)      // [0, 1, 20, 3, 4]\n\n// Sort\nlist.Sort(collections.CompareFunc[int]())\n\n// Filter\nevens := list.Filter(func(n int) bool { return n%2 == 0 })\n\n// Iterate in reverse\nfor v := range list.Reversed() {\n    fmt.Println(v)\n}\n```\n\n### LinkedList\n\nDoubly-linked list with O(1) head/tail operations and O(n) random access.\n\n**When to use LinkedList vs ArrayList:**\n- Use `LinkedList` when you frequently insert/remove at the beginning or need stable iterators\n- Use `ArrayList` when you need fast random access by index or iterate sequentially\n\n**Complexity:**\n| Operation | LinkedList | ArrayList |\n|-----------|------------|-----------|\n| Add (append) | O(1) | O(1) amortized |\n| AddFirst/RemoveFirst | O(1) | O(n) |\n| Get/Set by index | O(n) | O(1) |\n| Insert at index | O(n) | O(n) |\n\n**Constructors:**\n\n```go\nfunc NewLinkedList[T any]() List[T]\nfunc NewLinkedListFrom[T any](elements ...T) List[T]\n```\n\n**Example:**\n\n```go\nlist := collections.NewLinkedListFrom(\"a\", \"b\", \"c\")\n\n// O(1) operations at ends\nfirst, _ := list.RemoveFirst()  // \"a\"\nlist.Add(\"d\")                   // append: O(1)\n\n// O(n) random access\nv, _ := list.Get(1)  // \"c\" (need to traverse)\n\n// Iterate\nfor v := range list.Seq() {\n    fmt.Println(v)  // \"b\", \"c\", \"d\"\n}\n```\n\n### Concurrent List Implementations\n\nFor concurrent scenarios, three specialized list implementations are available:\n\n#### COWList (Copy-on-Write List)\n\nA copy-on-write list that provides lock-free reads and atomic writes by copying the entire underlying slice on modifications.\n\n**Constructors:**\n\n```go\nfunc NewCOWList[T any]() List[T]\nfunc NewCOWListFrom[T any](elements ...T) List[T]\n```\n\n#### SegmentedList\n\nA concurrent list using segmented locking for better write concurrency than COWList.\n\n**Constructors:**\n\n```go\nfunc NewSegmentedList[T any]() List[T]\nfunc NewSegmentedListWithSegments[T any](segmentCount int) List[T]\nfunc NewSegmentedListFrom[T any](elements ...T) List[T]\n```\n\n#### LockFreeList\n\nA lock-free concurrent linked list using CAS operations based on Harris's algorithm with logical deletion.\n\n**Constructors:**\n\n```go\nfunc NewLockFreeList[T any](eq Equaler[T]) List[T]\nfunc NewLockFreeListOrdered[T comparable]() List[T]\nfunc NewLockFreeListFrom[T any](eq Equaler[T], elements ...T) List[T]\n```\n\n**Note:** Due to logical deletion and node recycling, there is a potential ABA risk (implementation uses best-effort CAS). Suitable for scenarios that tolerate occasional retries.\n\n### Concurrent List Comparison\n\n| Feature | COWList | SegmentedList | LockFreeList |\n|---------|---------|---------------|--------------|\n| **Read Performance** | O(1) lock-free | O(1) with segment lock | O(n) traversal |\n| **Write Performance** | O(n) copy | O(1) amortized per segment | O(1) CAS at head |\n| **Memory Overhead** | High (full copy on write) | Low (segment metadata) | Medium (node + deleted flag) |\n| **Consistency** | Snapshot reads | Segment-level atomic | Eventual (logical deletion) |\n| **Best For** | Read-heavy, rare writes | Balanced read/write | High contention, frequent add/remove |\n| **Size Accuracy** | Exact | Exact | Approximate |\n| **Random Access** | O(1) | O(1) | O(n) |\n| **Iteration** | Snapshot | Snapshot | Snapshot |\n\n**When to use which:**\n- **COWList**: Ideal for read-heavy workloads where writes are infrequent (e.g., configuration lists, caches)\n- **SegmentedList**: Balanced read/write workloads with moderate concurrency\n- **LockFreeList**: High-contention scenarios where progress guarantees matter more than exact counts\n\n**Atomicity:**\n\n| Operation | COWList | SegmentedList | LockFreeList |\n|-----------|---------|---------------|--------------|\n| Get/Contains | Atomic (snapshot) | Atomic (segment lock) | Atomic |\n| Add/Insert | Atomic (full copy) | Atomic (segment lock) | Best-effort CAS |\n| Remove | Atomic (full copy) | Atomic (may cross segments) | Best-effort CAS |\n| Size | Exact | Exact | Approximate |\n| Iteration | Snapshot | Snapshot | Snapshot |\n\n---\n\n## Stacks\n\n### Stack Interface\n\n`Stack[T]` is a LIFO (last-in-first-out) collection.\n\n| Method | Description |\n|--------|-------------|\n| `Size() int` | Returns the number of elements |\n| `IsEmpty() bool` | Reports whether the stack is empty |\n| `Clear()` | Removes all elements |\n| `String() string` | Returns a string representation |\n| `Push(element T)` | Adds element to top |\n| `PushAll(elements ...T)` | Adds all to top (last becomes top) |\n| `Pop() (T, bool)` | Removes and returns top |\n| `Peek() (T, bool)` | Returns top without removing |\n| `ToSlice() []T` | Returns elements bottom to top |\n| `Seq() iter.Seq[T]` | Returns sequence top to bottom (LIFO) |\n\n### ArrayStack\n\nSlice-backed stack with O(1) push/pop.\n\n**Constructors:**\n\n```go\nfunc NewArrayStack[T any]() Stack[T]\nfunc NewArrayStackWithCapacity[T any](capacity int) Stack[T]\nfunc NewArrayStackFrom[T any](elements ...T) Stack[T]\n```\n\n**Example:**\n\n```go\nstack := collections.NewArrayStack[int]()\n\nstack.Push(1)\nstack.Push(2)\nstack.Push(3)\n\ntop, _ := stack.Peek()  // 3\nv, _ := stack.Pop()     // 3\nv, _ = stack.Pop()      // 2\n\n// Iterate in LIFO order\nfor v := range stack.Seq() {\n    fmt.Println(v)  // 1\n}\n```\n\n---\n\n## Queues\n\n### Queue Interface\n\n`Queue[T]` is a FIFO (first-in-first-out) collection.\n\n| Method | Description |\n|--------|-------------|\n| `Size() int` | Returns the number of elements |\n| `IsEmpty() bool` | Reports whether the queue is empty |\n| `Clear()` | Removes all elements |\n| `String() string` | Returns a string representation |\n| `Enqueue(element T)` | Adds element to back |\n| `EnqueueAll(elements ...T)` | Adds all to back |\n| `Dequeue() (T, bool)` | Removes and returns front |\n| `Peek() (T, bool)` | Returns front without removing |\n| `ToSlice() []T` | Returns elements front to back |\n| `Seq() iter.Seq[T]` | Returns sequence front to back (FIFO) |\n\n### ArrayQueue\n\nSlice-backed queue with amortized O(1) operations.\n\n**Constructors:**\n\n```go\nfunc NewArrayQueue[T any]() Queue[T]\nfunc NewArrayQueueWithCapacity[T any](capacity int) Queue[T]\nfunc NewArrayQueueFrom[T any](elements ...T) Queue[T]\n```\n\n**Example:**\n\n```go\nqueue := collections.NewArrayQueue[string]()\n\nqueue.Enqueue(\"first\")\nqueue.Enqueue(\"second\")\nqueue.Enqueue(\"third\")\n\nfront, _ := queue.Peek()    // \"first\"\nv, _ := queue.Dequeue()     // \"first\"\nv, _ = queue.Dequeue()      // \"second\"\n\n// Iterate in FIFO order\nfor v := range queue.Seq() {\n    fmt.Println(v)  // \"third\"\n}\n```\n\n### PriorityQueue\n\nHeap-based priority queue with O(log n) push/pop and O(1) peek. By default uses min-heap (smallest element has highest priority).\n\n**Constructors:**\n\n```go\nfunc NewPriorityQueue[T any](cmp Comparator[T]) PriorityQueue[T]\nfunc NewPriorityQueueOrdered[T Ordered]() PriorityQueue[T]           // min-heap\nfunc NewMaxPriorityQueue[T Ordered]() PriorityQueue[T]               // max-heap\nfunc NewPriorityQueueWithCapacity[T any](cmp Comparator[T], capacity int) PriorityQueue[T]\nfunc NewPriorityQueueFrom[T any](cmp Comparator[T], elements ...T) PriorityQueue[T]\n```\n\n**ToSlice vs ToSortedSlice:**\n- `ToSlice()` returns elements in heap order (not sorted) - O(n)\n- `ToSortedSlice()` returns elements sorted by priority - O(n log n)\n\n**Example (min-heap):**\n\n```go\n// Min-heap: smallest element has highest priority\npq := collections.NewPriorityQueueOrdered[int]()\npq.PushAll(5, 1, 3, 2, 4)\n\nv, _ := pq.Pop()  // 1 (smallest)\nv, _ = pq.Pop()   // 2\nv, _ = pq.Peek()  // 3 (without removing)\n\n// ToSlice: heap order (not sorted)\n// ToSortedSlice: priority order (sorted)\nsorted := pq.ToSortedSlice()  // [3, 4, 5]\n```\n\n**Example (max-heap):**\n\n```go\n// Max-heap: largest element has highest priority\npq := collections.NewMaxPriorityQueue[int]()\npq.PushAll(5, 1, 3, 2, 4)\n\nv, _ := pq.Pop()  // 5 (largest)\nv, _ = pq.Pop()   // 4\n```\n\n---\n\n## Deques\n\n### Deque Interface\n\n`Deque[T]` is a double-ended queue supporting insertion and removal at both ends.\n\n| Method | Description |\n|--------|-------------|\n| `Size() int` | Returns the number of elements |\n| `IsEmpty() bool` | Reports whether the deque is empty |\n| `Clear()` | Removes all elements |\n| `String() string` | Returns a string representation |\n| `PushFront(element T)` | Adds element to front |\n| `PopFront() (T, bool)` | Removes and returns front |\n| `PeekFront() (T, bool)` | Returns front without removing |\n| `PushBack(element T)` | Adds element to back |\n| `PopBack() (T, bool)` | Removes and returns back |\n| `PeekBack() (T, bool)` | Returns back without removing |\n| `ToSlice() []T` | Returns elements front to back |\n| `Seq() iter.Seq[T]` | Returns sequence front to back |\n| `Reversed() iter.Seq[T]` | Returns sequence back to front |\n\n### ArrayDeque\n\nCircular buffer-backed deque with O(1) operations at both ends.\n\n**Constructors:**\n\n```go\nfunc NewArrayDeque[T any]() Deque[T]\nfunc NewArrayDequeWithCapacity[T any](capacity int) Deque[T]\nfunc NewArrayDequeFrom[T any](elements ...T) Deque[T]\n```\n\n**Example:**\n\n```go\ndeque := collections.NewArrayDeque[int]()\n\n// Use as stack (LIFO)\ndeque.PushBack(1)\ndeque.PushBack(2)\nv, _ := deque.PopBack()  // 2\n\n// Use as queue (FIFO)\ndeque.PushBack(3)\nv, _ = deque.PopFront()  // 1\n\n// Double-ended operations\ndeque.PushFront(0)\ndeque.PushBack(4)\n\n// Iterate both directions\nfor v := range deque.Seq() {\n    fmt.Println(v)  // front to back\n}\n\nfor v := range deque.Reversed() {\n    fmt.Println(v)  // back to front\n}\n```\n\n---\n\n## License\n\nMIT, see [LICENSE](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Filxqx%2Fgo-collections","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Filxqx%2Fgo-collections","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Filxqx%2Fgo-collections/lists"}