collection

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2025 License: MIT Imports: 4 Imported by: 0

README

collection

Test Go Report Card codecov Latest version License Badge Go Reference

English | 中文

Generics collections framework for Golang.

[!NOTE] This package requires Go version 1.18+.

Overview

This package provides the following data structure interfaces and implementations:

  • Collection: The root interface of most of the structures in this package (without Dict).

  • List: An ordered collection (also known as a sequence).

    • ArrayList: The implementation of List based on Go built-in slice structure.

    • LinkedList: The implementation of List based on doubly linked list.

    • CopyOnWriteArrayList: The thread safe implementation of List based on copy-on-write strategy.

    • Stack: The stack implementation based on ArrayList.

  • Set: A collection interface that contains no duplicate elements.

    • HashSet: The implementation of Set based on Go built-in map structure.

    • SyncSet: The thread safe implementation of Set based on sync.Map.

    • DictSet: The thread safe Set based on RWMutex.

  • Dict: A object that maps keys to values, and it cannot contain duplicate key.

    • HashDict: The implementation of Dictionary based on Go built-in map structure.

    • SyncDict: The thread safe implementation of dictionary based on sync.Map.

    • DictDict: The thread safe dictionary based on RWMutex.

Installation

You can install this package by the following command.

go get -u github.com/ghosind/collection

After installation, you can import it by the following code.

import "github.com/ghosind/collection"

Examples

ArrayList Examples

Create an integer list, add and get elements from the list.

// import "github.com/ghosind/collection/list"

l := list.NewArrayList[int]()
l.Add(10)
l.Add(20)
l.Add(30)
log.Print(l.Get(1)) // 20
HashSet Examples

Create a string set, add and test elements in the set.

// import "github.com/ghosind/collection/set"

fruits := set.NewHashSet[string]()

fruits.Add("Apple")
fruits.Add("Banana")

log.Print(fruits.Contains("Banana")) // true
log.Print(fruits.Contains("Lemon")) // false
HashDict Examples
// import "github.com/ghosind/collection/dict"

languages := dict.NewHashDict[string, int]()

languages.Put("C", 1972)
languages.Put("Go", 2007)

log.Print(languages.GetDefault("C", 0)) // 1972

Testing

Run unit tests for the whole repository:

go test ./...

Run benchmarks (all packages):

go test -bench=. -benchmem ./...

Run benchmarks for a single package (example: dict):

go test ./dict -bench=. -run=^$ -benchmem

Benchmarks (Apple M2 sample results)

Below are sample benchmark results run on an Apple M2 machine. Your results may vary depending on Go version and system load.

Dict benchmarks with Get/Put:

BenchmarkHashDictGet-8          74139873                15.95 ns/op
BenchmarkHashDictPut-8          34336933                31.73 ns/op
BenchmarkLockDictGet-8          14385025                84.57 ns/op
BenchmarkLockDictPut-8          10031228               119.8 ns/op
BenchmarkSyncDictGet-8          191864160                5.795 ns/op
BenchmarkSyncDictPut-8           9078417               129.7 ns/op

Set benchmarks with Add and Contains:

BenchmarkHashSet-8      65497208                20.00 ns/op
BenchmarkLockSet-8       9549130               127.4 ns/op
BenchmarkSyncSet-8      61220974                20.90 ns/op

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrOutOfBounds indicates that the index is out of the valid range.
	ErrOutOfBounds = errors.New("index out of bounds")
)

Functions

This section is empty.

Types

type Collection

type Collection[T any] interface {
	Iterable[T]
	Stringer
	JSONMarshaler
	JSONUnmarshaler

	// Add adds the specified element to this collection.
	Add(e T) bool

	// AddAll adds all of the elements in the this collection.
	AddAll(c ...T) bool

	// Clear removes all of the elements from this collection.
	Clear()

	// Contains returns true if this collection contains the specified element.
	Contains(e T) bool

	// ContainsAll returns true if this collection contains all of the elements in the specified
	// collection.
	ContainsAll(c ...T) bool

	// Equals compares this collection with the object pass from parameter.
	Equals(o any) bool

	// ForEach performs the given handler for each elements in the collection until all elements
	// have been processed or the handler returns an error.
	ForEach(func(e T) error) error

	// IsEmpty returns true if this collection contains no elements.
	IsEmpty() bool

	// Remove removes the specified element from this collection.
	Remove(e T) bool

	// RemoveAll removes all of the elements in the specified collection from this collection.
	RemoveAll(c ...T) bool

	// RemoveIf removes all of the elements of this collection that satisfy the given predicate.
	RemoveIf(f func(T) bool) bool

	// RetainAll retains only the elements in this collection that are contained in the specified
	// collection.
	RetainAll(c ...T) bool

	// Size returns the number of elements in this collection.
	Size() int

	// ToSlice returns a slice containing all of the elements in this collection.
	ToSlice() []T
}

Collection is the root interface for this collections framework hierarchy.

type Dict added in v0.3.0

type Dict[K comparable, V any] interface {
	Iterable2[K, V]
	DictIter[K, V]
	Stringer
	JSONMarshaler
	JSONUnmarshaler

	// Clear removes all key-value pairs in this dictionary.
	Clear()

	// Clone returns a copy of this dictionary.
	Clone() Dict[K, V]

	// ContainsKey returns true if this dictionary contains a key-value pair with the specified key.
	ContainsKey(k K) bool

	// Equals compares this dictionary with the object pass from parameter.
	Equals(o any) bool

	// ForEach performs the given handler for each key-value pairs in the dictionary until all pairs
	// have been processed or the handler returns an error.
	ForEach(handler func(k K, v V) error) error

	// Get returns the value which associated to the specified key.
	Get(k K) (V, bool)

	// GetDefault returns the value associated with the specified key, and returns the default value
	// if this dictionary contains no pair with the key.
	GetDefault(k K, defaultVal V) V

	// IsEmpty returns true if this dictionary is empty.
	IsEmpty() bool

	// Keys returns a slice that contains all the keys in this dictionary.
	Keys() []K

	// Put associate the specified value with the specified key in this dictionary.
	Put(k K, v V) V

	// Remove removes the key-value pair with the specified key.
	Remove(k K) V

	// Replace replaces the value for the specified key only if it is currently in this dictionary.
	Replace(k K, v V) (V, bool)

	// Size returns the number of key-value pairs in this dictionary.
	Size() int

	// Values returns a slice that contains all the values in this dictionary.
	Values() []V
}

Dictionary is a object that maps keys to values, and it cannot contain duplicate key.

type DictIter added in v0.4.0

type DictIter[K comparable, V any] interface {
	// KeysIter returns an iterator over the keys in the dictionary.
	KeysIter() iter.Seq[K]
	// ValuesIter returns an iterator over the values in the dictionary.
	ValuesIter() iter.Seq[V]
}

type Iterable added in v0.3.0

type Iterable[T any] interface {
	// Iter returns an iterator of all elements in this collection.
	Iter() iter.Seq[T]
}

type Iterable2 added in v0.3.0

type Iterable2[K comparable, V any] interface {
	// Iter returns an iterator of all key-value pairs in this collection.
	Iter() iter.Seq2[K, V]
}

type JSONMarshaler added in v0.5.0

type JSONMarshaler json.Marshaler

JSONMarshaler is an interface that wraps the basic MarshalJSON method.

type JSONUnmarshaler added in v0.5.0

type JSONUnmarshaler json.Unmarshaler

JSONUnmarshaler is an interface that wraps the basic UnmarshalJSON method.

type List added in v0.3.0

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

	// AddAtIndex inserts the specified element to the specified position in this list.
	AddAtIndex(i int, e T)

	// Clone returns a copy of this list.
	Clone() List[T]

	// Get returns the element at the specified position in this list.
	Get(i int) T

	// IndexOf returns the index of the first occurrence of the specified element in this list, or -1
	// if this list does not contain the element.
	IndexOf(e T) int

	// LastIndexOf returns the index of the last occurrence of the specified element in this list, or
	// -1 if this list does not contain the element.
	LastIndexOf(e T) int

	// RemoveAtIndex removes the element at the specified position in this list.
	RemoveAtIndex(i int) T

	// Set replaces the element at the specified position in this list with the specified element.
	Set(i int, e T) T
}

List is an ordered collection.

type Set

type Set[T comparable] interface {
	Collection[T]

	// Clone returns a copy of this set.
	Clone() Set[T]
}

Set is a collection interface that contains no duplicate elements.

type Stringer added in v0.5.0

type Stringer fmt.Stringer

Stringer is an interface that wraps the basic String method.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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