collections

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2026 License: MIT Imports: 16 Imported by: 5

README

go-collections

Go Reference Go Report Card Build Status codecov

Generic, 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.

Table of Contents

Features

  • Type-Safe Generics: All collections are fully generic with compile-time type safety
  • Type-Safe Generics: All collections are fully generic with compile-time type safety
  • Interface Segregation: Small, focused interfaces composed into higher-level ones
  • Go 1.25+ Iteration: Native support for iter.Seq and iter.Seq2 for seamless for-range loops
  • Consistent API: Uniform naming across Set/Map/List; (value, ok) return patterns
  • Concurrent Variants: Thread-safe collections with atomic operations
  • No Reflection: Zero runtime reflection for maximum performance
  • Sorted Collections: B-Tree and Skip List backed sorted sets and maps
  • Memory Efficient: Optimized to prevent memory leaks with slices.Delete and proper capacity management

Requirements

  • Go 1.25 or later (uses iter.Seq/iter.Seq2, testing.B.Loop, built-in min/max)

Installation

go get github.com/coldsmirk/go-collections

Quick Start

package main

import (
    "fmt"
    "github.com/coldsmirk/go-collections"
)

func main() {
    // Create a HashSet
    set := collections.NewHashSetFrom(1, 2, 3, 4, 5)

    // Iterate using for-range with iter.Seq
    for v := range set.Seq() {
        fmt.Println(v)
    }

    // Set operations
    other := collections.NewHashSetFrom(4, 5, 6, 7)
    union := set.Union(other)
    intersection := set.Intersection(other)

    fmt.Printf("Union size: %d\n", union.Size())
    fmt.Printf("Intersection size: %d\n", intersection.Size())

    // Create a HashMap
    m := collections.NewHashMap[string, int]()
    m.Put("one", 1)
    m.Put("two", 2)

    if v, ok := m.Get("one"); ok {
        fmt.Printf("one = %d\n", v)
    }

    // Create a sorted TreeSet
    sorted := collections.NewTreeSetOrdered[int]()
    sorted.AddAll(5, 3, 1, 4, 2)

    // Iterate in sorted order
    for v := range sorted.Seq() {
        fmt.Println(v) // 1, 2, 3, 4, 5
    }
}

Constraints and Helpers

Type Constraints
// Ordered is a constraint for types that support <, ==, > operators.
// Aliases cmp.Ordered from the standard library.
type Ordered = cmp.Ordered

// Comparator compares two values: negative if a < b, zero if a == b, positive if a > b.
type Comparator[T any] func(a, b T) int

// Equaler reports whether two values are equal.
type Equaler[T any] func(a, b T) bool
Helper Functions
// EqualFunc returns a default Equaler for comparable types using ==.
func EqualFunc[T comparable]() Equaler[T]

// CompareFunc returns a Comparator for Ordered types using cmp.Compare.
func CompareFunc[T Ordered]() Comparator[T]

Usage:

// Using EqualFunc for list operations
list := collections.NewArrayListFrom(1, 2, 3, 2, 1)
list.Remove(2, collections.EqualFunc[int]())

// Using CompareFunc for sorting
list.Sort(collections.CompareFunc[int]())

Sets

Set Interface

Set[T] is an unordered collection of unique elements.

Method Description
Size() int Returns the number of elements
IsEmpty() bool Reports whether the set is empty
IsNotEmpty() bool Reports whether the set contains at least one element
Clear() Removes all elements
ToSlice() []T Returns a snapshot slice of all elements
String() string Returns a string representation
Seq() iter.Seq[T] Returns a sequence for for-range
ForEach(action func(T) bool) Iterates elements; stops if action returns false
Add(element T) bool Inserts element if absent; returns true if set changed
AddAll(elements ...T) int Inserts all elements; returns count added
AddSeq(seq iter.Seq[T]) int Inserts from sequence; returns count added
Remove(element T) bool Removes element; returns true if removed
RemoveAll(elements ...T) int Removes all elements; returns count removed
RemoveSeq(seq iter.Seq[T]) int Removes from sequence; returns count removed
RemoveFunc(predicate func(T) bool) int Removes elements satisfying predicate
RetainFunc(predicate func(T) bool) int Keeps only elements satisfying predicate
Pop() (T, bool) Removes and returns an arbitrary element
Contains(element T) bool Reports whether element exists
ContainsAll(elements ...T) bool Reports whether all elements exist
ContainsAny(elements ...T) bool Reports whether any element exists
Union(other Set[T]) Set[T] Returns s ∪ other
Intersection(other Set[T]) Set[T] Returns s ∩ other
Difference(other Set[T]) Set[T] Returns s - other
SymmetricDifference(other Set[T]) Set[T] Returns (s - other) ∪ (other - s)
IsSubsetOf(other Set[T]) bool Reports whether s ⊆ other
IsSupersetOf(other Set[T]) bool Reports whether s ⊇ other
IsProperSubsetOf(other Set[T]) bool Reports whether s ⊂ other
IsProperSupersetOf(other Set[T]) bool Reports whether s ⊃ other
IsDisjoint(other Set[T]) bool Reports whether s and other have no common elements
Equals(other Set[T]) bool Reports whether sets are equal
Clone() Set[T] Returns a shallow copy
Filter(predicate func(T) bool) Set[T] Returns new set with matching elements
Find(predicate func(T) bool) (T, bool) Returns first matching element
Any(predicate func(T) bool) bool Returns true if any element matches
Every(predicate func(T) bool) bool Returns true if all elements match
SortedSet Interface

SortedSet[T] extends Set[T] with sorted order operations.

Method Description
First() (T, bool) Returns the smallest element
Last() (T, bool) Returns the largest element
Min() (T, bool) Alias for First
Max() (T, bool) Alias for Last
PopFirst() (T, bool) Removes and returns the smallest element
PopLast() (T, bool) Removes and returns the largest element
Floor(x T) (T, bool) Returns greatest element ≤ x
Ceiling(x T) (T, bool) Returns smallest element ≥ x
Lower(x T) (T, bool) Returns greatest element < x
Higher(x T) (T, bool) Returns smallest element > x
Range(from, to T, action func(T) bool) Iterates elements in [from, to]
RangeSeq(from, to T) iter.Seq[T] Returns sequence for [from, to]
Ascend(action func(T) bool) Iterates in ascending order
Descend(action func(T) bool) Iterates in descending order
AscendFrom(pivot T, action func(T) bool) Iterates elements ≥ pivot ascending
DescendFrom(pivot T, action func(T) bool) Iterates elements ≤ pivot descending
Reversed() iter.Seq[T] Returns descending sequence
SubSet(from, to T) SortedSet[T] Returns elements in [from, to]
HeadSet(to T, inclusive bool) SortedSet[T] Returns elements < to (or ≤)
TailSet(from T, inclusive bool) SortedSet[T] Returns elements > from (or ≥)
Rank(x T) int Returns 0-based rank; -1 if absent
GetByRank(rank int) (T, bool) Returns element at rank
CloneSorted() SortedSet[T] Returns shallow copy as SortedSet
HashSet

Hash-based unordered set backed by map[T]struct{}.

Constructors:

func NewHashSet[T comparable]() Set[T]
func NewHashSetWithCapacity[T comparable](capacity int) Set[T]
func NewHashSetFrom[T comparable](elements ...T) Set[T]

Example:

set := collections.NewHashSetFrom("apple", "banana", "cherry")

set.Add("date")
set.Remove("banana")

for fruit := range set.Seq() {
    fmt.Println(fruit)
}

// Set algebra
other := collections.NewHashSetFrom("cherry", "date", "elderberry")
union := set.Union(other)
intersection := set.Intersection(other)
TreeSet

Sorted set backed by B-Tree. Maintains elements in comparator order.

Constructors:

func NewTreeSet[T any](c Comparator[T]) SortedSet[T]
func NewTreeSetOrdered[T Ordered]() SortedSet[T]
func NewTreeSetFrom[T any](c Comparator[T], elements ...T) SortedSet[T]

Example:

// For Ordered types (int, string, etc.)
set := collections.NewTreeSetOrdered[int]()
set.AddAll(5, 3, 1, 4, 2)

first, _ := set.First()  // 1
last, _ := set.Last()    // 5

// Range query
set.Range(2, 4, func(v int) bool {
    fmt.Println(v)  // 2, 3, 4
    return true
})

// Custom comparator (reverse order)
reverseSet := collections.NewTreeSet(func(a, b int) int {
    return b - a  // Descending
})
ConcurrentHashSet

Thread-safe hash set backed by xsync.MapOf.

Constructors:

func NewConcurrentHashSet[T comparable]() ConcurrentSet[T]
func NewConcurrentHashSetFrom[T comparable](elements ...T) ConcurrentSet[T]

Additional Methods (ConcurrentSet):

Method Description
AddIfAbsent(element T) bool Atomically adds if absent
RemoveAndGet(element T) (T, bool) Atomically removes and returns

Example:

set := collections.NewConcurrentHashSet[int]()

// Safe for concurrent use
go func() { set.Add(1) }()
go func() { set.Add(2) }()

// Atomic operations
if set.AddIfAbsent(3) {
    fmt.Println("3 was added")
}
ConcurrentTreeSet

Thread-safe sorted set using RWMutex-protected TreeSet.

Constructors:

func NewConcurrentTreeSet[T any](cmpT Comparator[T]) ConcurrentSortedSet[T]
func NewConcurrentTreeSetOrdered[T Ordered]() ConcurrentSortedSet[T]
func NewConcurrentTreeSetFrom[T any](cmpT Comparator[T], elements ...T) ConcurrentSortedSet[T]
ConcurrentSkipSet

Lock-free concurrent sorted set backed by skip list. For Ordered types only.

Constructors:

func NewConcurrentSkipSet[T Ordered]() ConcurrentSortedSet[T]
func NewConcurrentSkipSetFrom[T Ordered](elements ...T) ConcurrentSortedSet[T]

Maps

Map Interface

Map[K, V] is a collection that maps keys to values.

Method Description
Size() int Returns the number of entries
IsEmpty() bool Reports whether the map is empty
IsNotEmpty() bool Reports whether the map contains at least one entry
Clear() Removes all entries
String() string Returns a string representation
Put(key K, value V) (V, bool) Associates value with key; returns (old, existed)
PutIfAbsent(key K, value V) (V, bool) Stores if absent; returns (value, inserted)
PutAll(other Map[K, V]) Copies all entries from other
PutSeq(seq iter.Seq2[K, V]) int Copies from sequence; returns keys changed
Get(key K) (V, bool) Returns (value, exists)
GetOrDefault(key K, defaultValue V) V Returns value or default
Remove(key K) (V, bool) Removes key; returns (old, existed)
RemoveIf(key K, value V, eq Equaler[V]) bool Removes if value matches
ContainsKey(key K) bool Reports whether key exists
ContainsValue(value V, eq Equaler[V]) bool Reports whether value exists (O(n))
RemoveKeys(keys ...K) int Removes keys; returns count
RemoveKeysSeq(seq iter.Seq[K]) int Removes from sequence
RemoveFunc(predicate func(K, V) bool) int Removes matching entries
Compute(key K, remapping func(K, V, bool) (V, bool)) (V, bool) Recomputes mapping
ComputeIfAbsent(key K, mapping func(K) V) V Computes if absent
ComputeIfPresent(key K, remapping func(K, V) (V, bool)) (V, bool) Recomputes if present
Merge(key K, value V, remapping func(V, V) (V, bool)) (V, bool) Merges with existing
Replace(key K, value V) (V, bool) Replaces if present
ReplaceIf(key K, old, new V, eq Equaler[V]) bool Replaces if value matches
ReplaceAll(function func(K, V) V) Replaces all values
Keys() []K Returns all keys
Values() []V Returns all values
Entries() []Entry[K, V] Returns all entries
ForEach(action func(K, V) bool) Iterates entries
Seq() iter.Seq2[K, V] Returns (key, value) sequence
SeqKeys() iter.Seq[K] Returns keys sequence
SeqValues() iter.Seq[V] Returns values sequence
Clone() Map[K, V] Returns shallow copy
Filter(predicate func(K, V) bool) Map[K, V] Returns filtered map
Equals(other Map[K, V], valueEq Equaler[V]) bool Reports equality
SortedMap Interface

SortedMap[K, V] extends Map[K, V] with sorted key operations.

Method Description
FirstKey() (K, bool) Returns smallest key
LastKey() (K, bool) Returns largest key
FirstEntry() (Entry[K, V], bool) Returns entry with smallest key
LastEntry() (Entry[K, V], bool) Returns entry with largest key
PopFirst() (Entry[K, V], bool) Removes smallest-key entry
PopLast() (Entry[K, V], bool) Removes largest-key entry
FloorKey(k K) (K, bool) Returns greatest key ≤ k
CeilingKey(k K) (K, bool) Returns smallest key ≥ k
LowerKey(k K) (K, bool) Returns greatest key < k
HigherKey(k K) (K, bool) Returns smallest key > k
FloorEntry(k K) (Entry[K, V], bool) Returns entry with greatest key ≤ k
CeilingEntry(k K) (Entry[K, V], bool) Returns entry with smallest key ≥ k
LowerEntry(k K) (Entry[K, V], bool) Returns entry with greatest key < k
HigherEntry(k K) (Entry[K, V], bool) Returns entry with smallest key > k
Range(from, to K, action func(K, V) bool) Iterates [from, to]
RangeSeq(from, to K) iter.Seq2[K, V] Returns sequence for [from, to]
RangeFrom(from K, action func(K, V) bool) Iterates keys ≥ from
RangeTo(to K, action func(K, V) bool) Iterates keys ≤ to
Ascend(action func(K, V) bool) Iterates ascending
Descend(action func(K, V) bool) Iterates descending
AscendFrom(pivot K, action func(K, V) bool) Iterates ≥ pivot ascending
DescendFrom(pivot K, action func(K, V) bool) Iterates ≤ pivot descending
Reversed() iter.Seq2[K, V] Returns descending sequence
SubMap(from, to K) SortedMap[K, V] Returns entries in [from, to]
HeadMap(to K, inclusive bool) SortedMap[K, V] Returns entries < to (or ≤)
TailMap(from K, inclusive bool) SortedMap[K, V] Returns entries > from (or ≥)
RankOfKey(key K) int Returns 0-based rank; -1 if absent
GetByRank(rank int) (Entry[K, V], bool) Returns entry at rank
CloneSorted() SortedMap[K, V] Returns shallow copy as SortedMap
Entry Type
type Entry[K, V any] struct {
    Key   K
    Value V
}

// Unpack returns the key and value for convenient destructuring.
func (e Entry[K, V]) Unpack() (K, V)
HashMap

Hash-based unordered map backed by map[K]V.

Constructors:

func NewHashMap[K comparable, V any]() Map[K, V]
func NewHashMapWithCapacity[K comparable, V any](capacity int) Map[K, V]
func NewHashMapFrom[K comparable, V any](src map[K]V) Map[K, V]

Additional Interface:

**Example:**

```go
m := collections.NewHashMap[string, int]()
m.Put("one", 1)
m.Put("two", 2)
m.Put("three", 3)

// Get with existence check
if v, ok := m.Get("two"); ok {
    fmt.Printf("two = %d\n", v)
}

// Iterate
for k, v := range m.Seq() {
    fmt.Printf("%s: %d\n", k, v)
}

// Compute operations
m.ComputeIfAbsent("four", func(k string) int {
    return len(k)  // 4
})
TreeMap

Sorted map backed by B-Tree.

Constructors:

func NewTreeMap[K any, V any](cmpK Comparator[K]) SortedMap[K, V]
func NewTreeMapOrdered[K Ordered, V any]() SortedMap[K, V]
func NewTreeMapFrom[K comparable, V any](cmpK Comparator[K], m map[K]V) SortedMap[K, V]

Example:

m := collections.NewTreeMapOrdered[int, string]()
m.Put(3, "three")
m.Put(1, "one")
m.Put(2, "two")

// Iterate in sorted key order
for k, v := range m.Seq() {
    fmt.Printf("%d: %s\n", k, v)  // 1, 2, 3
}

// Navigation
floor, _ := m.FloorKey(2)      // 2
ceiling, _ := m.CeilingKey(2)  // 2
lower, _ := m.LowerKey(2)      // 1
higher, _ := m.HigherKey(2)    // 3
ConcurrentHashMap

Thread-safe hash map backed by xsync.MapOf.

Constructors:

func NewConcurrentHashMap[K comparable, V any]() ConcurrentMap[K, V]
func NewConcurrentHashMapFrom[K comparable, V any](src map[K]V) ConcurrentMap[K, V]

Additional Methods (ConcurrentMap):

Method Description
GetOrCompute(key K, compute func() V) (V, bool) Atomically get or compute
RemoveAndGet(key K) (V, bool) Atomically removes and returns
PutIfAbsent(key K, value V) (V, bool) Atomically stores if absent
CompareAndSwap(key K, old, new V, eq Equaler[V]) bool Atomic CAS
CompareAndDelete(key K, value V, eq Equaler[V]) bool Atomic compare-and-delete

Example:

m := collections.NewConcurrentHashMap[string, int]()

// Safe for concurrent use
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
    wg.Add(1)
    go func(n int) {
        defer wg.Done()
        m.Put(fmt.Sprintf("key%d", n), n)
    }(i)
}
wg.Wait()

// Atomic operations
v, computed := m.GetOrCompute("expensive", func() int {
    return expensiveCalculation()
})
ConcurrentTreeMap

Thread-safe sorted map using RWMutex-protected TreeMap.

Constructors:

func NewConcurrentTreeMap[K any, V any](cmpK Comparator[K]) ConcurrentSortedMap[K, V]
func NewConcurrentTreeMapOrdered[K Ordered, V any]() ConcurrentSortedMap[K, V]
func NewConcurrentTreeMapFrom[K comparable, V any](cmpK Comparator[K], m map[K]V) ConcurrentSortedMap[K, V]
ConcurrentSkipMap

Lock-free concurrent sorted map backed by skip list. For Ordered keys only.

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.

Constructors:

func NewConcurrentSkipMap[K Ordered, V any]() ConcurrentSortedMap[K, V]
func NewConcurrentSkipMapFrom[K Ordered, V any](src map[K]V) ConcurrentSortedMap[K, V]

Lists

List Interface

List[T] is an ordered collection with index-based access.

Method Description
Size() int Returns the number of elements
IsEmpty() bool Reports whether the list is empty
IsNotEmpty() bool Reports whether the list contains at least one element
Clear() Removes all elements
ToSlice() []T Returns a snapshot slice
String() string Returns a string representation
Seq() iter.Seq[T] Returns a sequence for for-range
ForEach(action func(T) bool) Iterates elements
Get(index int) (T, bool) Returns element at index
Set(index int, element T) (T, bool) Replaces element; returns old
First() (T, bool) Returns first element
Last() (T, bool) Returns last element
Add(element T) Appends element
AddAll(elements ...T) Appends all elements
AddSeq(seq iter.Seq[T]) Appends from sequence
Insert(index int, element T) bool Inserts at index
InsertAll(index int, elements ...T) bool Inserts all at index
RemoveAt(index int) (T, bool) Removes at index
Remove(element T, eq Equaler[T]) bool Removes first occurrence
RemoveFirst() (T, bool) Removes first element
RemoveLast() (T, bool) Removes last element
RemoveFunc(predicate func(T) bool) int Removes matching elements
RetainFunc(predicate func(T) bool) int Keeps matching elements
IndexOf(element T, eq Equaler[T]) int Returns first index; -1 if absent
LastIndexOf(element T, eq Equaler[T]) int Returns last index; -1 if absent
Contains(element T, eq Equaler[T]) bool Reports whether element exists
Find(predicate func(T) bool) (T, bool) Returns first matching element
FindIndex(predicate func(T) bool) int Returns first matching index
SubList(from, to int) List[T] Returns elements in [from, to)
Reversed() iter.Seq[T] Returns reverse sequence
Clone() List[T] Returns shallow copy
Filter(predicate func(T) bool) List[T] Returns filtered list
Sort(cmp Comparator[T]) Sorts in place
Any(predicate func(T) bool) bool Returns true if any match
Every(predicate func(T) bool) bool Returns true if all match
ArrayList

Dynamic array-backed list with O(1) append and O(n) insert/remove.

Constructors:

func NewArrayList[T any]() List[T]
func NewArrayListWithCapacity[T any](capacity int) List[T]
func NewArrayListFrom[T any](elements ...T) List[T]

Example:

list := collections.NewArrayListFrom(1, 2, 3)

list.Add(4)
list.Insert(0, 0)  // [0, 1, 2, 3, 4]

v, _ := list.Get(2)  // 2
list.Set(2, 20)      // [0, 1, 20, 3, 4]

// Sort
list.Sort(collections.CompareFunc[int]())

// Filter
evens := list.Filter(func(n int) bool { return n%2 == 0 })

// Iterate in reverse
for v := range list.Reversed() {
    fmt.Println(v)
}
LinkedList

Doubly-linked list with O(1) head/tail operations and O(n) random access.

When to use LinkedList vs ArrayList:

  • Use LinkedList when you frequently insert/remove at the beginning or need stable iterators
  • Use ArrayList when you need fast random access by index or iterate sequentially

Complexity:

Operation LinkedList ArrayList
Add (append) O(1) O(1) amortized
AddFirst/RemoveFirst O(1) O(n)
Get/Set by index O(n) O(1)
Insert at index O(n) O(n)

Constructors:

func NewLinkedList[T any]() List[T]
func NewLinkedListFrom[T any](elements ...T) List[T]

Example:

list := collections.NewLinkedListFrom("a", "b", "c")

// O(1) operations at ends
first, _ := list.RemoveFirst()  // "a"
list.Add("d")                   // append: O(1)

// O(n) random access
v, _ := list.Get(1)  // "c" (need to traverse)

// Iterate
for v := range list.Seq() {
    fmt.Println(v)  // "b", "c", "d"
}
Concurrent List Implementations

For concurrent scenarios, three specialized list implementations are available:

COWList (Copy-on-Write List)

A copy-on-write list that provides lock-free reads and atomic writes by copying the entire underlying slice on modifications.

Constructors:

func NewCOWList[T any]() List[T]
func NewCOWListFrom[T any](elements ...T) List[T]
SegmentedList

A concurrent list using segmented locking for better write concurrency than COWList.

Constructors:

func NewSegmentedList[T any]() List[T]
func NewSegmentedListWithSegments[T any](segmentCount int) List[T]
func NewSegmentedListFrom[T any](elements ...T) List[T]
LockFreeList

A lock-free concurrent linked list using CAS operations based on Harris's algorithm with logical deletion.

Constructors:

func NewLockFreeList[T any](eq Equaler[T]) List[T]
func NewLockFreeListOrdered[T comparable]() List[T]
func NewLockFreeListFrom[T any](eq Equaler[T], elements ...T) List[T]

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.

Concurrent List Comparison
Feature COWList SegmentedList LockFreeList
Read Performance O(1) lock-free O(1) with segment lock O(n) traversal
Write Performance O(n) copy O(1) amortized per segment O(1) CAS at head
Memory Overhead High (full copy on write) Low (segment metadata) Medium (node + deleted flag)
Consistency Snapshot reads Segment-level atomic Eventual (logical deletion)
Best For Read-heavy, rare writes Balanced read/write High contention, frequent add/remove
Size Accuracy Exact Exact Approximate
Random Access O(1) O(1) O(n)
Iteration Snapshot Snapshot Snapshot

When to use which:

  • COWList: Ideal for read-heavy workloads where writes are infrequent (e.g., configuration lists, caches)
  • SegmentedList: Balanced read/write workloads with moderate concurrency
  • LockFreeList: High-contention scenarios where progress guarantees matter more than exact counts

Atomicity:

Operation COWList SegmentedList LockFreeList
Get/Contains Atomic (snapshot) Atomic (segment lock) Atomic
Add/Insert Atomic (full copy) Atomic (segment lock) Best-effort CAS
Remove Atomic (full copy) Atomic (may cross segments) Best-effort CAS
Size Exact Exact Approximate
Iteration Snapshot Snapshot Snapshot

Stacks

Stack Interface

Stack[T] is a LIFO (last-in-first-out) collection.

Method Description
Size() int Returns the number of elements
IsEmpty() bool Reports whether the stack is empty
IsNotEmpty() bool Reports whether the stack contains at least one element
Clear() Removes all elements
String() string Returns a string representation
Push(element T) Adds element to top
PushAll(elements ...T) Adds all to top (last becomes top)
Pop() (T, bool) Removes and returns top
Peek() (T, bool) Returns top without removing
ToSlice() []T Returns elements bottom to top
Seq() iter.Seq[T] Returns sequence top to bottom (LIFO)
ArrayStack

Slice-backed stack with O(1) push/pop.

Constructors:

func NewArrayStack[T any]() Stack[T]
func NewArrayStackWithCapacity[T any](capacity int) Stack[T]
func NewArrayStackFrom[T any](elements ...T) Stack[T]

Example:

stack := collections.NewArrayStack[int]()

stack.Push(1)
stack.Push(2)
stack.Push(3)

top, _ := stack.Peek()  // 3
v, _ := stack.Pop()     // 3
v, _ = stack.Pop()      // 2

// Iterate in LIFO order
for v := range stack.Seq() {
    fmt.Println(v)  // 1
}

Queues

Queue Interface

Queue[T] is a FIFO (first-in-first-out) collection.

Method Description
Size() int Returns the number of elements
IsEmpty() bool Reports whether the queue is empty
IsNotEmpty() bool Reports whether the queue contains at least one element
Clear() Removes all elements
String() string Returns a string representation
Enqueue(element T) Adds element to back
EnqueueAll(elements ...T) Adds all to back
Dequeue() (T, bool) Removes and returns front
Peek() (T, bool) Returns front without removing
ToSlice() []T Returns elements front to back
Seq() iter.Seq[T] Returns sequence front to back (FIFO)
ArrayQueue

Slice-backed queue with amortized O(1) operations.

Constructors:

func NewArrayQueue[T any]() Queue[T]
func NewArrayQueueWithCapacity[T any](capacity int) Queue[T]
func NewArrayQueueFrom[T any](elements ...T) Queue[T]

Example:

queue := collections.NewArrayQueue[string]()

queue.Enqueue("first")
queue.Enqueue("second")
queue.Enqueue("third")

front, _ := queue.Peek()    // "first"
v, _ := queue.Dequeue()     // "first"
v, _ = queue.Dequeue()      // "second"

// Iterate in FIFO order
for v := range queue.Seq() {
    fmt.Println(v)  // "third"
}
PriorityQueue

Heap-based priority queue with O(log n) push/pop and O(1) peek. By default uses min-heap (smallest element has highest priority).

Constructors:

func NewPriorityQueue[T any](cmp Comparator[T]) PriorityQueue[T]
func NewPriorityQueueOrdered[T Ordered]() PriorityQueue[T]           // min-heap
func NewMaxPriorityQueue[T Ordered]() PriorityQueue[T]               // max-heap
func NewPriorityQueueWithCapacity[T any](cmp Comparator[T], capacity int) PriorityQueue[T]
func NewPriorityQueueFrom[T any](cmp Comparator[T], elements ...T) PriorityQueue[T]

ToSlice vs ToSortedSlice:

  • ToSlice() returns elements in heap order (not sorted) - O(n)
  • ToSortedSlice() returns elements sorted by priority - O(n log n)

Example (min-heap):

// Min-heap: smallest element has highest priority
pq := collections.NewPriorityQueueOrdered[int]()
pq.PushAll(5, 1, 3, 2, 4)

v, _ := pq.Pop()  // 1 (smallest)
v, _ = pq.Pop()   // 2
v, _ = pq.Peek()  // 3 (without removing)

// ToSlice: heap order (not sorted)
// ToSortedSlice: priority order (sorted)
sorted := pq.ToSortedSlice()  // [3, 4, 5]

Example (max-heap):

// Max-heap: largest element has highest priority
pq := collections.NewMaxPriorityQueue[int]()
pq.PushAll(5, 1, 3, 2, 4)

v, _ := pq.Pop()  // 5 (largest)
v, _ = pq.Pop()   // 4

Deques

Deque Interface

Deque[T] is a double-ended queue supporting insertion and removal at both ends.

Method Description
Size() int Returns the number of elements
IsEmpty() bool Reports whether the deque is empty
IsNotEmpty() bool Reports whether the deque contains at least one element
Clear() Removes all elements
String() string Returns a string representation
PushFront(element T) Adds element to front
PopFront() (T, bool) Removes and returns front
PeekFront() (T, bool) Returns front without removing
PushBack(element T) Adds element to back
PopBack() (T, bool) Removes and returns back
PeekBack() (T, bool) Returns back without removing
ToSlice() []T Returns elements front to back
Seq() iter.Seq[T] Returns sequence front to back
Reversed() iter.Seq[T] Returns sequence back to front
ArrayDeque

Circular buffer-backed deque with O(1) operations at both ends.

Constructors:

func NewArrayDeque[T any]() Deque[T]
func NewArrayDequeWithCapacity[T any](capacity int) Deque[T]
func NewArrayDequeFrom[T any](elements ...T) Deque[T]

Example:

deque := collections.NewArrayDeque[int]()

// Use as stack (LIFO)
deque.PushBack(1)
deque.PushBack(2)
v, _ := deque.PopBack()  // 2

// Use as queue (FIFO)
deque.PushBack(3)
v, _ = deque.PopFront()  // 1

// Double-ended operations
deque.PushFront(0)
deque.PushBack(4)

// Iterate both directions
for v := range deque.Seq() {
    fmt.Println(v)  // front to back
}

for v := range deque.Reversed() {
    fmt.Println(v)  // back to front
}

License

MIT, see LICENSE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Collection

type Collection[T any] interface {
	// Size returns the number of elements.
	Size() int
	// IsEmpty reports whether the collection contains no elements.
	IsEmpty() bool
	// IsNotEmpty reports whether the collection contains at least one element.
	IsNotEmpty() bool
	// Clear removes all elements from the collection.
	Clear()
	// ToSlice returns a snapshot slice of all elements.
	// The order depends on the concrete implementation.
	ToSlice() []T
	// String returns a string representation of the collection.
	String() string
}

Collection is the root interface for all collections. It exposes minimal, common capabilities that do not assume ordering.

type Comparator

type Comparator[T any] func(a, b T) int

Comparator compares two values: - negative if a < b - zero if a == b - positive if a > b

func CompareFunc

func CompareFunc[T Ordered]() Comparator[T]

CompareFunc returns a Comparator for Ordered types using cmp.Compare.

type ConcurrentMap

type ConcurrentMap[K, V any] interface {
	Map[K, V]

	// GetOrCompute atomically returns existing value or computes and stores a new one.
	// ATOMIC: This is a single atomic operation.
	// Returns (value, true) if computed (key was absent).
	GetOrCompute(key K, compute func() V) (V, bool)

	// RemoveAndGet atomically removes and returns the value for key.
	// ATOMIC: This is a single atomic operation.
	RemoveAndGet(key K) (V, bool)

	// CompareAndSwap replaces value if current equals old.
	// BEST-EFFORT: Atomic in ConcurrentHashMap; may race in ConcurrentSkipMap.
	CompareAndSwap(key K, old, new V, eq Equaler[V]) bool

	// CompareAndDelete deletes entry if current value equals provided.
	// BEST-EFFORT: Atomic in ConcurrentHashMap; may race in ConcurrentSkipMap.
	CompareAndDelete(key K, value V, eq Equaler[V]) bool
}

ConcurrentMap extends Map with atomic operations for concurrent use. All methods are safe for concurrent calls from multiple goroutines.

Atomicity guarantees:

  • ATOMIC: Get, Put, Remove, ContainsKey, PutIfAbsent, RemoveAndGet, GetOrCompute
  • BEST-EFFORT: CompareAndSwap, CompareAndDelete, RemoveIf, ReplaceIf (atomic in ConcurrentHashMap; may race in ConcurrentSkipMap)
  • NON-ATOMIC: PutAll, RemoveAll, RemoveFunc, ReplaceAll, Keys, Values, Entries, Seq

Implementation notes:

  • ConcurrentHashMap (xsync.MapOf): All operations are strictly atomic.
  • ConcurrentSkipMap (lock-free skip list): Single-key ops are atomic; compound ops like CompareAndSwap use load-then-modify and may race.

func NewConcurrentHashMap

func NewConcurrentHashMap[K comparable, V any]() ConcurrentMap[K, V]

NewConcurrentHashMap creates an empty concurrent map.

func NewConcurrentHashMapFrom

func NewConcurrentHashMapFrom[K comparable, V any](src map[K]V) ConcurrentMap[K, V]

NewConcurrentHashMapFrom creates a concurrent map copying entries from a standard map.

type ConcurrentSet

type ConcurrentSet[T any] interface {
	Set[T]

	// AddIfAbsent atomically inserts element only if currently absent.
	// ATOMIC: This is a single atomic operation.
	// Returns true if the element was added.
	AddIfAbsent(element T) bool

	// RemoveAndGet atomically removes and returns the element if present.
	// ATOMIC: This is a single atomic operation.
	RemoveAndGet(element T) (T, bool)
}

ConcurrentSet extends Set with atomic operations for concurrent use. All methods are safe for concurrent calls from multiple goroutines.

Atomicity guarantees:

  • ATOMIC: Add, Remove, Contains, AddIfAbsent, RemoveAndGet, Pop
  • BEST-EFFORT: RemoveFunc, RetainFunc (snapshot + individual removes)
  • NON-ATOMIC: AddAll, RemoveAll, AddSeq, RemoveSeq, Union, Intersection, etc.

func NewConcurrentHashSet

func NewConcurrentHashSet[T comparable]() ConcurrentSet[T]

NewConcurrentHashSet creates an empty concurrent set.

func NewConcurrentHashSetFrom

func NewConcurrentHashSetFrom[T comparable](elements ...T) ConcurrentSet[T]

NewConcurrentHashSetFrom creates a concurrent set and inserts elements.

type ConcurrentSortedMap

type ConcurrentSortedMap[K, V any] interface {
	SortedMap[K, V]
	ConcurrentMap[K, V]
}

ConcurrentSortedMap extends SortedMap with atomic operations. It embeds ConcurrentMap to inherit atomic methods.

Additional atomicity notes for sorted operations:

  • ATOMIC: FirstKey, LastKey, FirstEntry, LastEntry, FloorKey, CeilingKey
  • BEST-EFFORT: PopFirst, PopLast (may retry under contention)
  • NON-ATOMIC: Range, Ascend, Descend, SubMap, HeadMap, TailMap

func NewConcurrentSkipMap

func NewConcurrentSkipMap[K Ordered, V any]() ConcurrentSortedMap[K, V]

NewConcurrentSkipMap creates an empty concurrent sorted map.

func NewConcurrentSkipMapFrom

func NewConcurrentSkipMapFrom[K Ordered, V any](src map[K]V) ConcurrentSortedMap[K, V]

NewConcurrentSkipMapFrom creates a map populated from a standard Go map. Note: population is not atomic as a whole.

func NewConcurrentTreeMap

func NewConcurrentTreeMap[K any, V any](cmpK Comparator[K]) ConcurrentSortedMap[K, V]

NewConcurrentTreeMap creates an empty concurrent sorted map with a custom key comparator.

func NewConcurrentTreeMapFrom

func NewConcurrentTreeMapFrom[K comparable, V any](cmpK Comparator[K], m map[K]V) ConcurrentSortedMap[K, V]

NewConcurrentTreeMapFrom creates a map populated from a standard Go map.

func NewConcurrentTreeMapOrdered

func NewConcurrentTreeMapOrdered[K Ordered, V any]() ConcurrentSortedMap[K, V]

NewConcurrentTreeMapOrdered creates an empty map for Ordered keys.

type ConcurrentSortedSet

type ConcurrentSortedSet[T any] interface {
	SortedSet[T]
	ConcurrentSet[T]
}

ConcurrentSortedSet extends SortedSet with atomic operations. It embeds ConcurrentSet to inherit atomic methods.

Additional atomicity notes for sorted operations:

  • ATOMIC: First, Last, Floor, Ceiling, Lower, Higher
  • BEST-EFFORT: PopFirst, PopLast (may retry under contention)
  • NON-ATOMIC: Range, Ascend, Descend, SubSet, HeadSet, TailSet

func NewConcurrentSkipSet

func NewConcurrentSkipSet[T Ordered]() ConcurrentSortedSet[T]

NewConcurrentSkipSet creates an empty concurrent sorted set for Ordered types.

func NewConcurrentSkipSetFrom

func NewConcurrentSkipSetFrom[T Ordered](elements ...T) ConcurrentSortedSet[T]

NewConcurrentSkipSetFrom creates a set and inserts the given elements.

func NewConcurrentTreeSet

func NewConcurrentTreeSet[T any](cmpT Comparator[T]) ConcurrentSortedSet[T]

NewConcurrentTreeSet creates an empty concurrent sorted set with a custom comparator.

func NewConcurrentTreeSetFrom

func NewConcurrentTreeSetFrom[T any](cmpT Comparator[T], elements ...T) ConcurrentSortedSet[T]

NewConcurrentTreeSetFrom creates a set and inserts the given elements.

func NewConcurrentTreeSetOrdered

func NewConcurrentTreeSetOrdered[T Ordered]() ConcurrentSortedSet[T]

NewConcurrentTreeSetOrdered creates an empty set for Ordered types.

type Deque

type Deque[T any] interface {
	// Size returns the number of elements.
	Size() int
	// IsEmpty reports whether the deque is empty.
	IsEmpty() bool
	// IsNotEmpty reports whether the deque contains at least one element.
	IsNotEmpty() bool
	// Clear removes all elements.
	Clear()
	// String returns a string representation.
	String() string

	// --- Front Operations ---
	// PushFront adds an element to the front.
	PushFront(element T)
	// PopFront removes and returns the front element, or (zero, false) if empty.
	PopFront() (T, bool)
	// PeekFront returns the front element without removing it, or (zero, false) if empty.
	PeekFront() (T, bool)

	// --- Back Operations ---
	// PushBack adds an element to the back.
	PushBack(element T)
	// PopBack removes and returns the back element, or (zero, false) if empty.
	PopBack() (T, bool)
	// PeekBack returns the back element without removing it, or (zero, false) if empty.
	PeekBack() (T, bool)

	// ToSlice returns elements from front to back.
	ToSlice() []T
	// Seq returns a sequence from front to back.
	Seq() iter.Seq[T]
	// Reversed returns a sequence from back to front.
	Reversed() iter.Seq[T]
}

Deque is a double-ended queue supporting insertion and removal at both ends.

func NewArrayDeque

func NewArrayDeque[T any]() Deque[T]

NewArrayDeque creates an empty deque.

func NewArrayDequeFrom

func NewArrayDequeFrom[T any](elements ...T) Deque[T]

NewArrayDequeFrom creates a deque from elements (front to back in given order).

func NewArrayDequeWithCapacity

func NewArrayDequeWithCapacity[T any](capacity int) Deque[T]

NewArrayDequeWithCapacity creates a deque with capacity hint. If capacity <= 0, an empty buffer is created and will grow on first insert.

type Entry

type Entry[K, V any] struct {
	Key   K
	Value V
}

Entry represents a key-value pair.

func (Entry[K, V]) Unpack

func (e Entry[K, V]) Unpack() (K, V)

Unpack returns the key and value for convenient destructuring.

type Equaler

type Equaler[T any] func(a, b T) bool

Equaler reports whether two values are equal.

func EqualFunc

func EqualFunc[T comparable]() Equaler[T]

EqualFunc returns a default Equaler for comparable types using ==.

type GoMapView

type GoMapView[K comparable, V any] interface {
	// ToGoMap returns a standard Go map[K]V snapshot.
	ToGoMap() map[K]V
}

GoMapView marks implementations that can expose a native Go map snapshot. This requires comparable keys and is intentionally separate from Map[K,V].

type Iterable

type Iterable[T any] interface {
	// Seq returns a sequence for use with for-range:
	//   for v := range c.Seq() { ... }
	Seq() iter.Seq[T]
	// ForEach applies action to each element.
	// Iteration stops early if action returns false.
	ForEach(action func(element T) bool)
}

Iterable represents a collection that can be iterated. It provides Go 1.23+ for-range support via iter.Seq.

type List

type List[T any] interface {
	Collection[T]
	Iterable[T]

	// --- Positional Access ---
	// Get returns the element at index, or (zero, false) if out of bounds.
	Get(index int) (T, bool)
	// Set replaces the element at index. Returns (oldValue, true) if successful.
	Set(index int, element T) (T, bool)
	// First returns the first element, or (zero, false) if empty.
	First() (T, bool)
	// Last returns the last element, or (zero, false) if empty.
	Last() (T, bool)

	// --- Modification ---
	// Add appends the element to the end.
	Add(element T)
	// AddAll appends all elements to the end.
	AddAll(elements ...T)
	// AddSeq appends all elements from the sequence.
	AddSeq(seq iter.Seq[T])
	// Insert inserts the element at index, shifting subsequent elements right.
	// Returns false if index is out of bounds.
	Insert(index int, element T) bool
	// InsertAll inserts all elements at index, shifting subsequent elements right.
	InsertAll(index int, elements ...T) bool
	// RemoveAt removes the element at index. Returns (removed, true) if successful.
	RemoveAt(index int) (T, bool)
	// Remove removes the first occurrence of element. Returns true if removed.
	Remove(element T, eq Equaler[T]) bool
	// RemoveFirst removes and returns the first element.
	RemoveFirst() (T, bool)
	// RemoveLast removes and returns the last element.
	RemoveLast() (T, bool)
	// RemoveFunc removes all elements satisfying predicate. Returns count removed.
	RemoveFunc(predicate func(element T) bool) int
	// RetainFunc keeps only elements satisfying predicate. Returns count removed.
	RetainFunc(predicate func(element T) bool) int

	// --- Search ---
	// IndexOf returns the index of the first occurrence, or -1.
	IndexOf(element T, eq Equaler[T]) int
	// LastIndexOf returns the index of the last occurrence, or -1.
	LastIndexOf(element T, eq Equaler[T]) int
	// Contains reports whether element exists using eq for comparison.
	Contains(element T, eq Equaler[T]) bool
	// Find returns the first element satisfying predicate, or (zero, false).
	Find(predicate func(element T) bool) (T, bool)
	// FindIndex returns the index of the first element satisfying predicate, or -1.
	FindIndex(predicate func(element T) bool) int

	// --- Views ---
	// SubList returns a new list containing elements in [from, to).
	SubList(from, to int) List[T]
	// Reversed returns a sequence iterating in reverse order.
	Reversed() iter.Seq[T]

	// --- Transformations ---
	// Clone returns a shallow copy.
	Clone() List[T]
	// Filter returns a new list of elements satisfying predicate.
	Filter(predicate func(element T) bool) List[T]
	// Sort sorts elements in place using the comparator.
	Sort(cmp Comparator[T])

	// --- Aggregation ---
	// Any returns true if at least one element satisfies predicate.
	Any(predicate func(element T) bool) bool
	// Every returns true if all elements satisfy predicate.
	Every(predicate func(element T) bool) bool
}

List is an ordered collection that allows duplicate elements. Elements are accessible by integer index (0-based).

func NewArrayList

func NewArrayList[T any]() List[T]

NewArrayList creates an empty List.

func NewArrayListFrom

func NewArrayListFrom[T any](elements ...T) List[T]

NewArrayListFrom creates a List containing the provided elements.

func NewArrayListWithCapacity

func NewArrayListWithCapacity[T any](capacity int) List[T]

NewArrayListWithCapacity creates a List with capacity hint.

func NewCOWList

func NewCOWList[T any]() List[T]

NewCOWList creates an empty Copy-on-Write list.

func NewCOWListFrom

func NewCOWListFrom[T any](elements ...T) List[T]

NewCOWListFrom creates a COW list from elements.

func NewLinkedList

func NewLinkedList[T any]() List[T]

NewLinkedList creates an empty LinkedList.

func NewLinkedListFrom

func NewLinkedListFrom[T any](elements ...T) List[T]

NewLinkedListFrom creates a LinkedList containing the provided elements.

func NewLockFreeList

func NewLockFreeList[T any](eq Equaler[T]) List[T]

NewLockFreeList creates a new lock-free list. The equaler function is used for element comparison.

func NewLockFreeListFrom

func NewLockFreeListFrom[T any](eq Equaler[T], elements ...T) List[T]

NewLockFreeListFrom creates a lock-free list from elements.

func NewLockFreeListOrdered

func NewLockFreeListOrdered[T comparable]() List[T]

NewLockFreeListOrdered creates a lock-free list for ordered types.

func NewSegmentedList

func NewSegmentedList[T any]() List[T]

NewSegmentedList creates a new segmented list with default segment count.

func NewSegmentedListFrom

func NewSegmentedListFrom[T any](elements ...T) List[T]

NewSegmentedListFrom creates a segmented list from elements.

func NewSegmentedListWithSegments

func NewSegmentedListWithSegments[T any](segmentCount int) List[T]

NewSegmentedListWithSegments creates a segmented list with specified segment count.

type Map

type Map[K, V any] interface {
	// --- Basic Info ---
	// Size returns the number of entries.
	Size() int
	// IsEmpty reports whether the map has no entries.
	IsEmpty() bool
	// IsNotEmpty reports whether the map contains at least one entry.
	IsNotEmpty() bool
	// Clear removes all entries.
	Clear()
	// String returns a string representation.
	String() string

	// --- Basic Operations ---
	// Put associates value with key. Returns (oldValue, true) if key existed.
	Put(key K, value V) (V, bool)
	// PutIfAbsent stores value only if key is absent. Returns (existingOrNew, inserted).
	PutIfAbsent(key K, value V) (V, bool)
	// PutAll copies all entries from other into this map.
	PutAll(other Map[K, V])
	// PutSeq copies entries from a sequence. Returns number of keys changed.
	PutSeq(seq iter.Seq2[K, V]) int
	// Get returns (value, true) if key present; otherwise (zero, false).
	Get(key K) (V, bool)
	// GetOrDefault returns value for key or defaultValue if absent.
	GetOrDefault(key K, defaultValue V) V
	// Remove deletes key. Returns (oldValue, true) if key existed.
	Remove(key K) (V, bool)
	// RemoveIf deletes only if (key, value) matches. Returns true if removed.
	RemoveIf(key K, value V, eq Equaler[V]) bool

	// --- Query ---
	// ContainsKey reports whether key exists.
	ContainsKey(key K) bool
	// ContainsValue reports whether value exists (O(n)).
	ContainsValue(value V, eq Equaler[V]) bool

	// --- Bulk Operations ---
	// RemoveAll removes all specified keys. Returns count removed.
	RemoveAll(keys ...K) int
	// RemoveSeq removes keys from the sequence. Returns count removed.
	RemoveSeq(seq iter.Seq[K]) int
	// RemoveFunc removes entries where predicate returns true. Returns count removed.
	RemoveFunc(predicate func(key K, value V) bool) int

	// --- Compute Operations ---
	// Compute recomputes mapping for key.
	// If keep==false, the key is removed.
	Compute(key K, remapping func(key K, oldValue V, exists bool) (newValue V, keep bool)) (V, bool)
	// ComputeIfAbsent computes and stores value if key is absent.
	ComputeIfAbsent(key K, mapping func(key K) V) V
	// ComputeIfPresent recomputes value if key is present. If keep==false, removes key.
	ComputeIfPresent(key K, remapping func(key K, oldValue V) (newValue V, keep bool)) (V, bool)
	// Merge merges value with existing. If keep==false, removes key.
	Merge(key K, value V, remapping func(oldValue, newValue V) (mergedValue V, keep bool)) (V, bool)

	// --- Replace Operations ---
	// Replace sets value only if key is present. Returns (oldValue, true) if replaced.
	Replace(key K, value V) (V, bool)
	// ReplaceIf replaces only if current value equals oldValue. Returns true if replaced.
	ReplaceIf(key K, oldValue, newValue V, eq Equaler[V]) bool
	// ReplaceAll replaces each value with function(key, value).
	ReplaceAll(function func(key K, value V) V)

	// --- Views ---
	// Keys returns all keys as a slice.
	Keys() []K
	// Values returns all values as a slice.
	Values() []V
	// Entries returns all entries as a slice.
	Entries() []Entry[K, V]

	// --- Iteration ---
	// ForEach iterates over entries. Stops early if action returns false.
	ForEach(action func(key K, value V) bool)
	// Seq returns a sequence of (key, value) pairs.
	Seq() iter.Seq2[K, V]
	// SeqKeys returns a sequence of keys.
	SeqKeys() iter.Seq[K]
	// SeqValues returns a sequence of values.
	SeqValues() iter.Seq[V]

	// --- Transformations ---
	// Clone returns a shallow copy.
	Clone() Map[K, V]
	// Filter returns a new map with entries satisfying predicate.
	Filter(predicate func(key K, value V) bool) Map[K, V]

	// --- Comparison ---
	// Equals reports whether both maps contain the same entries.
	Equals(other Map[K, V], valueEq Equaler[V]) bool
}

Map is a collection that maps keys to values (unique keys).

func NewHashMap

func NewHashMap[K comparable, V any]() Map[K, V]

NewHashMap creates an empty Map.

func NewHashMapFrom

func NewHashMapFrom[K comparable, V any](src map[K]V) Map[K, V]

NewHashMapFrom creates a Map from a standard Go map (copying entries).

func NewHashMapWithCapacity

func NewHashMapWithCapacity[K comparable, V any](capacity int) Map[K, V]

NewHashMapWithCapacity creates an empty Map with an initial capacity hint.

type Ordered

type Ordered = cmp.Ordered

Ordered is a constraint for types that support <, ==, > operators. It aliases cmp.Ordered from the standard library.

type PriorityQueue

type PriorityQueue[T any] interface {
	// Size returns the number of elements.
	Size() int
	// IsEmpty reports whether the queue is empty.
	IsEmpty() bool
	// IsNotEmpty reports whether the queue contains at least one element.
	IsNotEmpty() bool
	// Clear removes all elements.
	Clear()
	// String returns a string representation.
	String() string

	// Push adds an element to the queue. O(log n).
	Push(element T)
	// PushAll adds all elements to the queue.
	PushAll(elements ...T)
	// Pop removes and returns the highest-priority element, or (zero, false) if empty. O(log n).
	Pop() (T, bool)
	// Peek returns the highest-priority element without removing it, or (zero, false) if empty. O(1).
	Peek() (T, bool)

	// ToSlice returns elements in heap order (not sorted).
	ToSlice() []T
	// ToSortedSlice returns elements in priority order (sorted).
	ToSortedSlice() []T
	// Seq returns a sequence in heap order (not sorted).
	Seq() iter.Seq[T]
}

PriorityQueue is a queue where elements are ordered by priority. The element with the highest priority (according to the comparator) is always at the front. By default, a min-heap is used (smallest element has highest priority). Use a reverse comparator for max-heap behavior.

func NewMaxPriorityQueue

func NewMaxPriorityQueue[T Ordered]() PriorityQueue[T]

NewMaxPriorityQueue creates a max-heap priority queue for Ordered types. Largest element has highest priority.

func NewPriorityQueue

func NewPriorityQueue[T any](cmp Comparator[T]) PriorityQueue[T]

NewPriorityQueue creates an empty priority queue with a custom comparator. The comparator determines priority: elements with smaller comparison values have higher priority (min-heap). Use a reverse comparator for max-heap.

func NewPriorityQueueFrom

func NewPriorityQueueFrom[T any](cmp Comparator[T], elements ...T) PriorityQueue[T]

NewPriorityQueueFrom creates a priority queue from elements.

func NewPriorityQueueOrdered

func NewPriorityQueueOrdered[T Ordered]() PriorityQueue[T]

NewPriorityQueueOrdered creates a min-heap priority queue for Ordered types. Smallest element has highest priority.

func NewPriorityQueueWithCapacity

func NewPriorityQueueWithCapacity[T any](cmp Comparator[T], capacity int) PriorityQueue[T]

NewPriorityQueueWithCapacity creates a priority queue with capacity hint.

func UnmarshalPriorityQueueGob

func UnmarshalPriorityQueueGob[T any](data []byte, comparator Comparator[T]) (PriorityQueue[T], error)

UnmarshalPriorityQueueGob deserializes a PriorityQueue from Gob. Requires a comparator to be provided.

func UnmarshalPriorityQueueJSON

func UnmarshalPriorityQueueJSON[T any](data []byte, comparator Comparator[T]) (PriorityQueue[T], error)

UnmarshalPriorityQueueJSON deserializes a PriorityQueue from JSON. Requires a comparator to be provided.

func UnmarshalPriorityQueueOrderedGob

func UnmarshalPriorityQueueOrderedGob[T Ordered](data []byte) (PriorityQueue[T], error)

UnmarshalPriorityQueueOrderedGob deserializes a PriorityQueue from Gob for Ordered types. Uses cmp.Compare as the default comparator.

func UnmarshalPriorityQueueOrderedJSON

func UnmarshalPriorityQueueOrderedJSON[T Ordered](data []byte) (PriorityQueue[T], error)

UnmarshalPriorityQueueOrderedJSON deserializes a PriorityQueue from JSON for Ordered types. Uses cmp.Compare as the default comparator.

type Queue

type Queue[T any] interface {
	// Size returns the number of elements.
	Size() int
	// IsEmpty reports whether the queue is empty.
	IsEmpty() bool
	// IsNotEmpty reports whether the queue contains at least one element.
	IsNotEmpty() bool
	// Clear removes all elements.
	Clear()
	// String returns a string representation.
	String() string

	// Enqueue adds an element to the back of the queue.
	Enqueue(element T)
	// EnqueueAll adds all elements to the back.
	EnqueueAll(elements ...T)
	// Dequeue removes and returns the front element, or (zero, false) if empty.
	Dequeue() (T, bool)
	// Peek returns the front element without removing it, or (zero, false) if empty.
	Peek() (T, bool)

	// ToSlice returns elements from front to back.
	ToSlice() []T
	// Seq returns a sequence from front to back (FIFO order).
	Seq() iter.Seq[T]
}

Queue is a FIFO (first-in-first-out) collection.

func NewArrayQueue

func NewArrayQueue[T any]() Queue[T]

NewArrayQueue creates an empty queue.

func NewArrayQueueFrom

func NewArrayQueueFrom[T any](elements ...T) Queue[T]

NewArrayQueueFrom creates a queue initialized with elements (front to back).

func NewArrayQueueWithCapacity

func NewArrayQueueWithCapacity[T any](capacity int) Queue[T]

NewArrayQueueWithCapacity creates a queue with capacity hint.

type Set

type Set[T any] interface {
	Collection[T]
	Iterable[T]

	// --- Modification ---
	// Add inserts the element if absent. Returns true if the set changed.
	Add(element T) bool
	// AddAll inserts all given elements. Returns the number of elements added.
	AddAll(elements ...T) int
	// AddSeq inserts all elements from the sequence. Returns the number added.
	AddSeq(seq iter.Seq[T]) int
	// Remove deletes the element if present. Returns true if removed.
	Remove(element T) bool
	// RemoveAll deletes all given elements. Returns the number removed.
	RemoveAll(elements ...T) int
	// RemoveSeq removes all elements from the sequence. Returns the number removed.
	RemoveSeq(seq iter.Seq[T]) int
	// RemoveFunc removes elements satisfying predicate. Returns count removed.
	RemoveFunc(predicate func(element T) bool) int
	// RetainFunc keeps only elements satisfying predicate. Returns count removed.
	RetainFunc(predicate func(element T) bool) int
	// Pop removes and returns an arbitrary element. Returns (zero, false) if empty.
	Pop() (T, bool)

	// --- Query ---
	// Contains reports whether element exists in the set.
	Contains(element T) bool
	// ContainsAll reports whether all elements exist in the set.
	ContainsAll(elements ...T) bool
	// ContainsAny reports whether any of the elements exist in the set.
	ContainsAny(elements ...T) bool

	// --- Set Algebra ---
	// Union returns a new set: s ∪ other.
	Union(other Set[T]) Set[T]
	// Intersection returns a new set: s ∩ other.
	Intersection(other Set[T]) Set[T]
	// Difference returns a new set: s - other.
	Difference(other Set[T]) Set[T]
	// SymmetricDifference returns a new set: (s - other) ∪ (other - s).
	SymmetricDifference(other Set[T]) Set[T]

	// --- Relations ---
	// IsSubsetOf reports whether all elements of s are in other.
	IsSubsetOf(other Set[T]) bool
	// IsSupersetOf reports whether s contains all elements of other.
	IsSupersetOf(other Set[T]) bool
	// IsProperSubsetOf reports whether s ⊂ other (subset but not equal).
	IsProperSubsetOf(other Set[T]) bool
	// IsProperSupersetOf reports whether s ⊃ other (superset but not equal).
	IsProperSupersetOf(other Set[T]) bool
	// IsDisjoint reports whether s and other have no elements in common.
	IsDisjoint(other Set[T]) bool
	// Equals reports whether s and other contain exactly the same elements.
	Equals(other Set[T]) bool

	// --- Transformations ---
	// Clone returns a shallow copy.
	Clone() Set[T]
	// Filter returns a new set of elements that satisfy predicate.
	Filter(predicate func(element T) bool) Set[T]

	// --- Search ---
	// Find returns the first element satisfying predicate, or (zero, false).
	Find(predicate func(element T) bool) (T, bool)
	// Any returns true if at least one element satisfies predicate.
	Any(predicate func(element T) bool) bool
	// Every returns true if all elements satisfy predicate (true for empty set).
	Every(predicate func(element T) bool) bool
}

Set is an unordered collection of unique elements. Ordering is not guaranteed unless a SortedSet is used.

func NewHashSet

func NewHashSet[T comparable]() Set[T]

NewHashSet creates an empty Set.

func NewHashSetFrom

func NewHashSetFrom[T comparable](elements ...T) Set[T]

NewHashSetFrom creates a Set and inserts all provided elements.

func NewHashSetWithCapacity

func NewHashSetWithCapacity[T comparable](capacity int) Set[T]

NewHashSetWithCapacity creates an empty Set with an initial capacity hint.

type SortedMap

type SortedMap[K, V any] interface {
	Map[K, V]

	// --- Extremes ---
	// FirstKey returns the smallest key, or (zero, false) if empty.
	FirstKey() (K, bool)
	// LastKey returns the largest key, or (zero, false) if empty.
	LastKey() (K, bool)
	// FirstEntry returns the entry with the smallest key.
	FirstEntry() (Entry[K, V], bool)
	// LastEntry returns the entry with the largest key.
	LastEntry() (Entry[K, V], bool)
	// PopFirst removes and returns the smallest-key entry.
	PopFirst() (Entry[K, V], bool)
	// PopLast removes and returns the largest-key entry.
	PopLast() (Entry[K, V], bool)

	// --- Navigation ---
	// FloorKey returns the greatest key <= k, or (zero, false).
	FloorKey(k K) (K, bool)
	// CeilingKey returns the smallest key >= k, or (zero, false).
	CeilingKey(k K) (K, bool)
	// LowerKey returns the greatest key < k, or (zero, false).
	LowerKey(k K) (K, bool)
	// HigherKey returns the smallest key > k, or (zero, false).
	HigherKey(k K) (K, bool)
	// FloorEntry returns entry with greatest key <= k.
	FloorEntry(k K) (Entry[K, V], bool)
	// CeilingEntry returns entry with smallest key >= k.
	CeilingEntry(k K) (Entry[K, V], bool)
	// LowerEntry returns entry with greatest key < k.
	LowerEntry(k K) (Entry[K, V], bool)
	// HigherEntry returns entry with smallest key > k.
	HigherEntry(k K) (Entry[K, V], bool)

	// --- Range Iteration ---
	// Range iterates entries with keys in [from, to] ascending.
	// If from > to, no elements are visited.
	Range(from, to K, action func(key K, value V) bool)
	// RangeSeq returns a sequence for entries with keys in [from, to] ascending.
	// If from > to, returns an empty sequence.
	RangeSeq(from, to K) iter.Seq2[K, V]
	// RangeFrom iterates entries with keys >= from.
	RangeFrom(from K, action func(key K, value V) bool)
	// RangeTo iterates entries with keys <= to.
	RangeTo(to K, action func(key K, value V) bool)

	// --- Ordered Iteration ---
	// Ascend iterates all entries in ascending key order.
	Ascend(action func(key K, value V) bool)
	// Descend iterates all entries in descending key order.
	Descend(action func(key K, value V) bool)
	// AscendFrom iterates entries with keys >= pivot ascending.
	AscendFrom(pivot K, action func(key K, value V) bool)
	// DescendFrom iterates entries with keys <= pivot descending.
	DescendFrom(pivot K, action func(key K, value V) bool)
	// Reversed returns a sequence iterating in descending key order.
	Reversed() iter.Seq2[K, V]

	// --- Views ---
	// SubMap returns entries with keys in [from, to].
	SubMap(from, to K) SortedMap[K, V]
	// HeadMap returns entries with keys < to (or <= if inclusive).
	HeadMap(to K, inclusive bool) SortedMap[K, V]
	// TailMap returns entries with keys > from (or >= if inclusive).
	TailMap(from K, inclusive bool) SortedMap[K, V]

	// --- Rank Operations ---
	// RankOfKey returns the 0-based rank of key, or -1 if not present.
	RankOfKey(key K) int
	// GetByRank returns the entry at rank, or (Entry{}, false).
	GetByRank(rank int) (Entry[K, V], bool)

	// --- Sorted Clone ---
	// CloneSorted returns a shallow copy as SortedMap.
	CloneSorted() SortedMap[K, V]
}

SortedMap is a Map that maintains entries in sorted key order.

func NewTreeMap

func NewTreeMap[K any, V any](cmpK Comparator[K]) SortedMap[K, V]

NewTreeMap creates an empty SortedMap with a custom key comparator.

func NewTreeMapFrom

func NewTreeMapFrom[K comparable, V any](cmpK Comparator[K], m map[K]V) SortedMap[K, V]

NewTreeMapFrom creates a TreeMap from a standard Go map (copying entries).

func NewTreeMapOrdered

func NewTreeMapOrdered[K Ordered, V any]() SortedMap[K, V]

NewTreeMapOrdered creates an empty TreeMap for Ordered keys.

func UnmarshalTreeMapGob

func UnmarshalTreeMapGob[K, V any](data []byte, comparator Comparator[K]) (SortedMap[K, V], error)

UnmarshalTreeMapGob deserializes a TreeMap from Gob. Requires a comparator to be provided.

func UnmarshalTreeMapJSON

func UnmarshalTreeMapJSON[K, V any](data []byte, comparator Comparator[K]) (SortedMap[K, V], error)

UnmarshalTreeMapJSON deserializes a TreeMap from JSON. Requires a comparator to be provided.

func UnmarshalTreeMapOrderedGob

func UnmarshalTreeMapOrderedGob[K Ordered, V any](data []byte) (SortedMap[K, V], error)

UnmarshalTreeMapOrderedGob deserializes a TreeMap from Gob for Ordered key types. Uses cmp.Compare as the default comparator for keys.

func UnmarshalTreeMapOrderedJSON

func UnmarshalTreeMapOrderedJSON[K Ordered, V any](data []byte) (SortedMap[K, V], error)

UnmarshalTreeMapOrderedJSON deserializes a TreeMap from JSON for Ordered key types. Uses cmp.Compare as the default comparator for keys.

type SortedSet

type SortedSet[T any] interface {
	Set[T]

	// --- Extremes ---
	// First returns the smallest element, or (zero, false) if empty.
	First() (T, bool)
	// Last returns the largest element, or (zero, false) if empty.
	Last() (T, bool)
	// Min is an alias of First for compatibility with other libraries.
	Min() (T, bool)
	// Max is an alias of Last for compatibility with other libraries.
	Max() (T, bool)
	// PopFirst removes and returns the smallest element.
	PopFirst() (T, bool)
	// PopLast removes and returns the largest element.
	PopLast() (T, bool)

	// --- Navigation ---
	// Floor returns the greatest element <= x, or (zero, false).
	Floor(x T) (T, bool)
	// Ceiling returns the smallest element >= x, or (zero, false).
	Ceiling(x T) (T, bool)
	// Lower returns the greatest element < x, or (zero, false).
	Lower(x T) (T, bool)
	// Higher returns the smallest element > x, or (zero, false).
	Higher(x T) (T, bool)

	// --- Range Iteration ---
	// Range iterates elements in [from, to] ascending.
	// If from > to, no elements are visited.
	Range(from, to T, action func(element T) bool)
	// RangeSeq returns a sequence for elements in [from, to] ascending.
	// If from > to, returns an empty sequence.
	RangeSeq(from, to T) iter.Seq[T]

	// --- Ordered Iteration ---
	// Ascend iterates all elements in ascending order.
	Ascend(action func(element T) bool)
	// Descend iterates all elements in descending order.
	Descend(action func(element T) bool)
	// AscendFrom iterates elements >= pivot in ascending order.
	AscendFrom(pivot T, action func(element T) bool)
	// DescendFrom iterates elements <= pivot in descending order.
	DescendFrom(pivot T, action func(element T) bool)
	// Reversed returns a descending sequence for for-range.
	Reversed() iter.Seq[T]

	// --- Views ---
	// SubSet returns a new set containing elements in [from, to].
	SubSet(from, to T) SortedSet[T]
	// HeadSet returns elements < to (or <= if inclusive).
	HeadSet(to T, inclusive bool) SortedSet[T]
	// TailSet returns elements > from (or >= if inclusive).
	TailSet(from T, inclusive bool) SortedSet[T]

	// --- Rank Operations ---
	// Rank returns the 0-based rank of x, or -1 if not present.
	Rank(x T) int
	// GetByRank returns the element at 0-based rank, or (zero, false).
	GetByRank(rank int) (T, bool)

	// --- Sorted Clone ---
	// CloneSorted returns a shallow copy as SortedSet.
	CloneSorted() SortedSet[T]
}

SortedSet is a Set that maintains elements in sorted order. Implementations may require T to satisfy Ordered, or accept a Comparator[T].

func NewTreeSet

func NewTreeSet[T any](c Comparator[T]) SortedSet[T]

NewTreeSet creates an empty SortedSet with a custom comparator.

func NewTreeSetFrom

func NewTreeSetFrom[T any](c Comparator[T], elements ...T) SortedSet[T]

NewTreeSetFrom creates a TreeSet and inserts all elements.

func NewTreeSetOrdered

func NewTreeSetOrdered[T Ordered]() SortedSet[T]

NewTreeSetOrdered creates an empty TreeSet for Ordered types.

func UnmarshalTreeSetGob

func UnmarshalTreeSetGob[T any](data []byte, comparator Comparator[T]) (SortedSet[T], error)

UnmarshalTreeSetGob deserializes a TreeSet from Gob. Requires a comparator to be provided.

func UnmarshalTreeSetJSON

func UnmarshalTreeSetJSON[T any](data []byte, comparator Comparator[T]) (SortedSet[T], error)

UnmarshalTreeSetJSON deserializes a TreeSet from JSON. Requires a comparator to be provided.

func UnmarshalTreeSetOrderedGob

func UnmarshalTreeSetOrderedGob[T Ordered](data []byte) (SortedSet[T], error)

UnmarshalTreeSetOrderedGob deserializes a TreeSet from Gob for Ordered types. Uses cmp.Compare as the default comparator.

func UnmarshalTreeSetOrderedJSON

func UnmarshalTreeSetOrderedJSON[T Ordered](data []byte) (SortedSet[T], error)

UnmarshalTreeSetOrderedJSON deserializes a TreeSet from JSON for Ordered types. Uses cmp.Compare as the default comparator.

type Stack

type Stack[T any] interface {
	// Size returns the number of elements.
	Size() int
	// IsEmpty reports whether the stack is empty.
	IsEmpty() bool
	// IsNotEmpty reports whether the stack contains at least one element.
	IsNotEmpty() bool
	// Clear removes all elements.
	Clear()
	// String returns a string representation.
	String() string

	// Push adds an element to the top of the stack.
	Push(element T)
	// PushAll adds all elements to the top (last element becomes top).
	PushAll(elements ...T)
	// Pop removes and returns the top element, or (zero, false) if empty.
	Pop() (T, bool)
	// Peek returns the top element without removing it, or (zero, false) if empty.
	Peek() (T, bool)

	// ToSlice returns elements from bottom to top.
	ToSlice() []T
	// Seq returns a sequence from top to bottom (LIFO order).
	Seq() iter.Seq[T]
}

Stack is a LIFO (last-in-first-out) collection.

func NewArrayStack

func NewArrayStack[T any]() Stack[T]

NewArrayStack creates an empty Stack.

func NewArrayStackFrom

func NewArrayStackFrom[T any](elements ...T) Stack[T]

NewArrayStackFrom creates a stack initialized with elements (bottom to top).

func NewArrayStackWithCapacity

func NewArrayStackWithCapacity[T any](capacity int) Stack[T]

NewArrayStackWithCapacity creates a stack with capacity hint.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL