g

package
v0.9.12 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2025 License: MIT Imports: 17 Imported by: 1

Documentation

Overview

Package g provides kinds of concurrent-safe/unsafe containers.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AVLTree

type AVLTree[K comparable, V any] struct {
	// contains filtered or unexported fields
}

AVLTree holds elements of the AVL tree.

func NewAVLTree

func NewAVLTree[K comparable, V any](comparator func(v1, v2 K) int, safe ...bool) *AVLTree[K, V]

NewAVLTree instantiates an AVL tree with the custom key comparators. The parameter `safe` is used to specify whether using tree in concurrent-safety, which is false in default.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	avlTree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		avlTree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(avlTree)

}
Output:
│       ┌── key5
│   ┌── key4
└── key3
    │   ┌── key2
    └── key1
        └── key0

func NewAVLTreeFrom

func NewAVLTreeFrom[K comparable, V any](comparator func(v1, v2 K) int, data map[K]V, safe ...bool) *AVLTree[K, V]

NewAVLTreeFrom instantiates an AVL tree with the custom key comparators and data map. The parameter `safe` is used to specify whether using tree in concurrent-safety, which is false in default.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	avlTree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		avlTree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	otherAvlTree := g.NewAVLTreeFrom(comparators.ComparatorString, avlTree.Map())
	fmt.Println(otherAvlTree)

	// May Output:
	// │   ┌── key5
	// │   │   └── key4
	// └── key3
	//     │   ┌── key2
	//     └── key1
	//         └── key0
}

func (*AVLTree[K, V]) Ceiling

func (tree *AVLTree[K, V]) Ceiling(key K) (ceiling *AVLTreeNode[K, V], found bool)

Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling node is found. Second return parameter is true if ceiling was found, otherwise false.

Ceiling node is defined as the smallest node that is larger than or equal to the given node. A ceiling node may not be found, either because the tree is empty, or because all nodes in the tree is smaller than the given node.

key should adhere to the comparators's type assertion, otherwise method panics.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewAVLTree[int, int](comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		if i != 50 {
			tree.Put(i, i)
		}
	}

	node, found := tree.Ceiling(1)
	if found {
		fmt.Println("CeilingEntry 1:", node.Key())
	}

	node, found = tree.Ceiling(50)
	if found {
		fmt.Println("CeilingEntry 50:", node.Key())
	}

	node, found = tree.Ceiling(100)
	if found {
		fmt.Println("CeilingEntry 100:", node.Key())
	}

	node, found = tree.Ceiling(-1)
	if found {
		fmt.Println("CeilingEntry -1:", node.Key())
	}

}
Output:
CeilingEntry 1: 1
CeilingEntry 50: 51
CeilingEntry -1: 1

func (*AVLTree[K, V]) Clear

func (tree *AVLTree[K, V]) Clear()

Clear removes all nodes from the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[int, string](comparators.ComparatorInt)
	for i := 0; i < 6; i++ {
		tree.Put(1000+i, "val"+gconv.String(i))
	}
	fmt.Println(tree.Size())

	tree.Clear()
	fmt.Println(tree.Size())

}
Output:
6
0

func (*AVLTree[K, V]) Clone

func (tree *AVLTree[K, V]) Clone(safe ...bool) Map[K, V]

Clone returns a new tree with a copy of current tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	avl := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		avl.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	tree := avl.Clone()

	fmt.Println(tree.Map())
	fmt.Println(tree.Size())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]
6

func (*AVLTree[K, V]) ContainsKey

func (tree *AVLTree[K, V]) ContainsKey(key K) bool

ContainsKey checks whether `key` exists in the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.ContainsKey("key1"))
	fmt.Println(tree.ContainsKey("key6"))

}
Output:
true
false

func (*AVLTree[K, V]) Floor

func (tree *AVLTree[K, V]) Floor(key K) (floor *AVLTreeNode[K, V], found bool)

Floor Finds floor node of the input key, return the floor node or nil if no floor node is found. Second return parameter is true if floor was found, otherwise false.

Floor node is defined as the largest node that is smaller than or equal to the given node. A floor node may not be found, either because the tree is empty, or because all nodes in the tree is larger than the given node.

key should adhere to the comparators's type assertion, otherwise method panics.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewAVLTree[int, int](comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		if i != 50 {
			tree.Put(i, i)
		}
	}

	node, found := tree.Floor(95)
	if found {
		fmt.Println("FloorEntry 95:", node.Key())
	}

	node, found = tree.Floor(50)
	if found {
		fmt.Println("FloorEntry 50:", node.Key())
	}

	node, found = tree.Floor(100)
	if found {
		fmt.Println("FloorEntry 100:", node.Key())
	}

	node, found = tree.Floor(0)
	if found {
		fmt.Println("FloorEntry 0:", node.Key())
	}

}
Output:
FloorEntry 95: 95
FloorEntry 50: 49
FloorEntry 100: 99

func (*AVLTree[K, V]) ForEach

func (tree *AVLTree[K, V]) ForEach(f func(key K, value V) bool)

ForEach is alias of ForEachAsc.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewAVLTree[int, int](comparators.ComparatorInt)
	for i := 0; i < 10; i++ {
		tree.Put(i, 10-i)
	}

	var totalKey, totalValue int
	tree.ForEach(func(key, value int) bool {
		totalKey += key
		totalValue += value

		return totalValue < 20
	})

	fmt.Println("totalKey:", totalKey)
	fmt.Println("totalValue:", totalValue)

}
Output:
totalKey: 3
totalValue: 27

func (*AVLTree[K, V]) ForEachAsc

func (tree *AVLTree[K, V]) ForEachAsc(f func(key K, value V) bool)

ForEachAsc iterates the tree readonly in ascending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewAVLTree[int, int](comparators.ComparatorInt)
	for i := 0; i < 10; i++ {
		tree.Put(i, 10-i)
	}

	tree.ForEachAsc(func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 0 , value: 10
key: 1 , value: 9
key: 2 , value: 8
key: 3 , value: 7
key: 4 , value: 6
key: 5 , value: 5
key: 6 , value: 4
key: 7 , value: 3
key: 8 , value: 2
key: 9 , value: 1

func (*AVLTree[K, V]) ForEachDesc

func (tree *AVLTree[K, V]) ForEachDesc(f func(key K, value V) bool)

ForEachDesc iterates the tree readonly in descending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewAVLTree[int, int](comparators.ComparatorInt)
	for i := 0; i < 10; i++ {
		tree.Put(i, 10-i)
	}

	tree.ForEachDesc(func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 9 , value: 1
key: 8 , value: 2
key: 7 , value: 3
key: 6 , value: 4
key: 5 , value: 5
key: 4 , value: 6
key: 3 , value: 7
key: 2 , value: 8
key: 1 , value: 9
key: 0 , value: 10

func (*AVLTree[K, V]) Get

func (tree *AVLTree[K, V]) Get(key K) (value V)

Get returns the value by given `key`, or empty value of type K if the key is not found in the map.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Get("key1"))
	fmt.Println(tree.Get("key10"))

}
Output:
val1

func (*AVLTree[K, V]) GetOrPut

func (tree *AVLTree[K, V]) GetOrPut(key K, value V) V

GetOrPut returns the value by key, or sets value with given `value` if it does not exist and then returns this value.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.GetOrPut("key1", "newVal1"))
	fmt.Println(tree.GetOrPut("key6", "val6"))

}
Output:
val1
val6

func (*AVLTree[K, V]) GetOrPutFunc

func (tree *AVLTree[K, V]) GetOrPutFunc(key K, f func() V) V

GetOrPutFunc returns the value by key, or sets value with returned value of callback function `f` if it does not exist and then returns this value.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.GetOrPutFunc("key1", func() string {
		return "newVal1"
	}))
	fmt.Println(tree.GetOrPutFunc("key6", func() string {
		return "val6"
	}))

}
Output:
val1
val6

func (*AVLTree[K, V]) IsEmpty

func (tree *AVLTree[K, V]) IsEmpty() bool

IsEmpty returns true if tree does not contain any nodes.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)

	fmt.Println(tree.IsEmpty())

	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.IsEmpty())

}
Output:
true
false

func (*AVLTree[K, V]) IteratorAscFrom

func (tree *AVLTree[K, V]) IteratorAscFrom(key K, match bool, f func(key K, value V) bool)

IteratorAscFrom iterates the tree readonly in ascending order with given callback function `f`. The parameter `key` specifies the start entry for iterating. The `match` specifies whether starting iterating if the `key` is fully matched, or else using index searching iterating. If `f` returns true, then it continues iterating; or false to stop.

Example (NoExistKey)
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		m[i] = i * 10
	}
	tree := g.NewAVLTreeFrom(comparators.ComparatorInt, m)

	tree.IteratorAscFrom(0, true, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Example (NoExistKeyAndMatchFalse)
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		m[i] = i * 10
	}
	tree := g.NewAVLTreeFrom(comparators.ComparatorInt, m)

	tree.IteratorAscFrom(6, false, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Example (Normal)
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		m[i] = i * 10
	}
	tree := g.NewAVLTreeFrom(comparators.ComparatorInt, m)

	tree.IteratorAscFrom(1, true, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 1 , value: 10
key: 2 , value: 20
key: 3 , value: 30
key: 4 , value: 40
key: 5 , value: 50

func (*AVLTree[K, V]) IteratorDescFrom

func (tree *AVLTree[K, V]) IteratorDescFrom(key K, match bool, f func(key K, value V) bool)

IteratorDescFrom iterates the tree readonly in descending order with given callback function `f`. The parameter `key` specifies the start entry for iterating. The `match` specifies whether starting iterating if the `key` is fully matched, or else using index searching iterating. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		m[i] = i * 10
	}
	tree := g.NewAVLTreeFrom(comparators.ComparatorInt, m)

	tree.IteratorDescFrom(5, true, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 5 , value: 50
key: 4 , value: 40
key: 3 , value: 30
key: 2 , value: 20
key: 1 , value: 10

func (*AVLTree[K, V]) IteratorFrom

func (tree *AVLTree[K, V]) IteratorFrom(key K, match bool, f func(key K, value V) bool)

IteratorFrom is alias of IteratorAscFrom.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		m[i] = i * 10
	}
	tree := g.NewAVLTreeFrom[int, int](comparators.ComparatorInt, m)

	tree.IteratorFrom(1, true, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 1 , value: 10
key: 2 , value: 20
key: 3 , value: 30
key: 4 , value: 40
key: 5 , value: 50

func (*AVLTree[K, V]) KeySet added in v0.9.10

func (tree *AVLTree[K, V]) KeySet() Set[K]

KeySet returns a set of the keys contained in the tree.

func (*AVLTree[K, V]) Keys

func (tree *AVLTree[K, V]) Keys() []K

Keys returns all keys in asc order.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 6; i > 0; i-- {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Keys())

}
Output:
[key1 key2 key3 key4 key5 key6]

func (*AVLTree[K, V]) Left

func (tree *AVLTree[K, V]) Left() *AVLTreeNode[K, V]

Left returns the minimum element of the AVL tree or nil if the tree is empty.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewAVLTree[int, int](comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		tree.Put(i, i)
	}
	fmt.Println(tree.Left().Key(), tree.Left().Value())

	emptyTree := g.NewAVLTree[int, int](comparators.ComparatorInt)
	fmt.Println(emptyTree.Left())

}
Output:
1 1
<nil>

func (*AVLTree[K, V]) Map

func (tree *AVLTree[K, V]) Map() map[K]V

Map returns all key-value items as map.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Map())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]

func (*AVLTree[K, V]) MapStrAny

func (tree *AVLTree[K, V]) MapStrAny() map[string]V

MapStrAny returns all key-value items as map[string]V.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[int, string](comparators.ComparatorInt)
	for i := 0; i < 6; i++ {
		tree.Put(1000+i, "val"+gconv.String(i))
	}

	fmt.Println(tree.MapStrAny())

}
Output:
map[1000:val0 1001:val1 1002:val2 1003:val3 1004:val4 1005:val5]

func (AVLTree[K, V]) MarshalJSON

func (tree AVLTree[K, V]) MarshalJSON() (jsonBytes []byte, err error)

MarshalJSON implements the interface MarshalJSON for json.Marshal.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/internal/json"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	bytes, err := json.Marshal(tree)
	if err == nil {
		fmt.Println(gconv.String(bytes))
	}

}
Output:
{"key0":"val0","key1":"val1","key2":"val2","key3":"val3","key4":"val4","key5":"val5"}

func (*AVLTree[K, V]) Print

func (tree *AVLTree[K, V]) Print()

Print prints the tree to stdout.

Example
package main

import (
	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	tree.Print()

}
Output:
│       ┌── key5
│   ┌── key4
└── key3
    │   ┌── key2
    └── key1
        └── key0

func (*AVLTree[K, V]) Put

func (tree *AVLTree[K, V]) Put(key K, value V)

Put inserts node into the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Map())
	fmt.Println(tree.Size())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]
6

func (*AVLTree[K, V]) PutIfAbsent

func (tree *AVLTree[K, V]) PutIfAbsent(key K, value V) bool

PutIfAbsent sets `value` to the map if the `key` does not exist, and then returns true. It returns false if `key` exists, and `value` would be ignored.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.PutIfAbsent("key1", "newVal1"))
	fmt.Println(tree.PutIfAbsent("key6", "val6"))

}
Output:
false
true

func (*AVLTree[K, V]) PutIfAbsentFunc

func (tree *AVLTree[K, V]) PutIfAbsentFunc(key K, f func() V) bool

PutIfAbsentFunc sets value with return value of callback function `f`, and then returns true. It returns false if `key` exists, and `value` would be ignored.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.PutIfAbsentFunc("key1", func() string {
		return "newVal1"
	}))
	fmt.Println(tree.PutIfAbsentFunc("key6", func() string {
		return "val6"
	}))

}
Output:
false
true

func (*AVLTree[K, V]) Puts

func (tree *AVLTree[K, V]) Puts(data map[K]V)

Puts batch sets key-values to the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)

	tree.Puts(map[string]string{
		"key1": "val1",
		"key2": "val2",
	})

	fmt.Println(tree.Map())
	fmt.Println(tree.Size())

}
Output:
map[key1:val1 key2:val2]
2

func (*AVLTree[K, V]) Remove

func (tree *AVLTree[K, V]) Remove(key K) (value V, removed bool)

Remove removes the node from the tree by key. key should adhere to the comparators's type assertion, otherwise method panics.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Remove("key1"))
	fmt.Println(tree.Remove("key6"))
	fmt.Println(tree.Map())

}
Output:
val1 true
 false
map[key0:val0 key2:val2 key3:val3 key4:val4 key5:val5]

func (*AVLTree[K, V]) Removes

func (tree *AVLTree[K, V]) Removes(keys []K)

Removes batch deletes values of the tree by `keys`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	removeKeys := make([]string, 2)
	removeKeys = append(removeKeys, "key1")
	removeKeys = append(removeKeys, "key6")

	tree.Removes(removeKeys)

	fmt.Println(tree.Map())

}
Output:
map[key0:val0 key2:val2 key3:val3 key4:val4 key5:val5]

func (*AVLTree[K, V]) Replace

func (tree *AVLTree[K, V]) Replace(data map[K]V)

Replace the data of the tree with given `data`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Map())

	data := map[string]string{
		"newKey0": "newVal0",
		"newKey1": "newVal1",
		"newKey2": "newVal2",
	}

	tree.Replace(data)

	fmt.Println(tree.Map())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]
map[newKey0:newVal0 newKey1:newVal1 newKey2:newVal2]

func (*AVLTree[K, V]) Right

func (tree *AVLTree[K, V]) Right() *AVLTreeNode[K, V]

Right returns the maximum element of the AVL tree or nil if the tree is empty.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewAVLTree[int, int](comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		tree.Put(i, i)
	}
	fmt.Println(tree.Right().Key(), tree.Right().Value())

	emptyTree := g.NewAVLTree[int, int](comparators.ComparatorInt)
	fmt.Println(emptyTree.Left())

}
Output:
99 99
<nil>

func (*AVLTree[K, V]) Search

func (tree *AVLTree[K, V]) Search(key K) (value V, found bool)

Search searches the tree with given `key`. Second return parameter `found` is true if key was found, otherwise false.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Search("key0"))
	fmt.Println(tree.Search("key6"))

}
Output:
val0 true
 false

func (*AVLTree[K, V]) Size

func (tree *AVLTree[K, V]) Size() int

Size returns number of nodes in the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)

	fmt.Println(tree.Size())

	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Size())

}
Output:
0
6

func (*AVLTree[K, V]) String

func (tree *AVLTree[K, V]) String() string

String returns a string representation of container

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.String())

}
Output:
│       ┌── key5
│   ┌── key4
└── key3
    │   ┌── key2
    └── key1
        └── key0

func (*AVLTree[K, V]) Values

func (tree *AVLTree[K, V]) Values() []V

Values returns all values in asc order based on the key.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewAVLTree[string, string](comparators.ComparatorString)
	for i := 6; i > 0; i-- {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Values())

}
Output:
[val1 val2 val3 val4 val5 val6]

type AVLTreeNode

type AVLTreeNode[K comparable, V any] struct {
	// contains filtered or unexported fields
}

AVLTreeNode is a single element within the tree.

func (*AVLTreeNode[K, V]) Key

func (n *AVLTreeNode[K, V]) Key() K

func (*AVLTreeNode[K, V]) Next

func (node *AVLTreeNode[K, V]) Next() *AVLTreeNode[K, V]

Next returns the next element in an inorder walk of the AVL tree.

func (*AVLTreeNode[K, V]) Prev

func (node *AVLTreeNode[K, V]) Prev() *AVLTreeNode[K, V]

Prev returns the previous element in an inorder walk of the AVL tree.

func (*AVLTreeNode[K, V]) Value

func (n *AVLTreeNode[K, V]) Value() V

type ArrayList

type ArrayList[T any] struct {
	// contains filtered or unexported fields
}

ArrayList is a golang array with rich features. It contains a concurrent-safe/unsafe switch, which should be set when its initialization and cannot be changed then.

func NewArrayList

func NewArrayList[T any](safe ...bool) *ArrayList[T]

NewArrayList creates and returns an empty array. The parameter `safe` is used to specify whether using array in concurrent-safety, which is false in default.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	// A normal array.
	a := g.NewArrayList[int]()

	// Adding items.
	for i := 0; i < 10; i++ {
		a.Add(i)
	}

	// Print the array length.
	fmt.Println(a.Len())

	// Print the array items.
	fmt.Println(a.Slice())

	// Retrieve item by index.
	fmt.Println(a.Get(6))

	// Check item existence.
	fmt.Println(a.Contains(6))
	fmt.Println(a.Contains(100))

	// Insert item before specified index.
	_ = a.InsertAfter(9, 11)
	// Insert item after specified index.
	_ = a.InsertBefore(10, 10)

	fmt.Println(a.Slice())

	// Modify item by index.
	_ = a.Set(0, 100)
	fmt.Println(a.Slice())

	fmt.Println(a.MustGet(0))

	// Search item and return its index.
	fmt.Println(a.Search(5))

	// Remove item by index.
	a.Remove(100)
	fmt.Println(a.Slice())

	// IsEmpty the array, removes all items of it.
	fmt.Println(a.Slice())
	a.Clear()
	fmt.Println(a.Slice())

}
Output:
10
[0 1 2 3 4 5 6 7 8 9]
6 true
true
false
[0 1 2 3 4 5 6 7 8 9 10 11]
[100 1 2 3 4 5 6 7 8 9 10 11]
100
5
[1 2 3 4 5 6 7 8 9 10 11]
[1 2 3 4 5 6 7 8 9 10 11]
[]

func NewArrayListFrom

func NewArrayListFrom[T any](array []T, safe ...bool) *ArrayList[T]

NewArrayListFrom is alias of NewArrayListFrom. See NewArrayListFrom.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	n := 10
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 10, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)
	fmt.Println(l.FrontAll())
	fmt.Println(l.BackAll())

	for i := 0; i < n; i++ {
		v, _ := l.PopFront()
		fmt.Print(v)
	}

	fmt.Println()
	fmt.Println(l.Len())

}
Output:
10
[1,2,3,4,5,6,7,8,9,10]
[1 2 3 4 5 6 7 8 9 10]
[10 9 8 7 6 5 4 3 2 1]
12345678910
0

func NewArrayListFromCopy

func NewArrayListFromCopy[T any](array []T, safe ...bool) *ArrayList[T]

NewArrayListFromCopy is alias of NewArrayFromCopy. See NewArrayFromCopy.

func NewArrayListRange

func NewArrayListRange(start, end, step int, safe ...bool) *ArrayList[int]

NewArrayListRange creates and returns an array by a range from `start` to `end` with step value `step`.

func NewArrayListSize

func NewArrayListSize[T any](size int, cap int, safe ...bool) *ArrayList[T]

NewArrayListSize create and returns an array with given size and cap. The parameter `safe` is used to specify whether using array in concurrent-safety, which is false in default.

func (*ArrayList[T]) Add

func (a *ArrayList[T]) Add(values ...T) bool

Add is alias of PushRight, please See PushRight.

func (*ArrayList[T]) AddAll

func (a *ArrayList[T]) AddAll(values Collection[T]) bool

AddAll adds all the elements in the specified collection to this collection. Returns true if this collection changed as a result of the call

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array1 := g.NewArrayListFrom[int]([]int{1, 2})
	array2 := g.NewArrayListFrom[int]([]int{3, 4})
	slice1 := []int{5, 6}
	slice2 := []int{7, 8}
	slice3 := []int{9, 0}
	fmt.Println(array1.Slice())
	array1.AddAll(array1)
	array1.AddAll(array2)
	array1.Add(slice1...)
	array1.Add(slice2...)
	array1.Add(slice3...)
	fmt.Println(array1.Slice())

}
Output:
[1 2]
[1 2 1 2 3 4 5 6 7 8 9 0]

func (*ArrayList[T]) Chunk

func (a *ArrayList[T]) Chunk(size int) [][]T

Chunk splits an array into multiple arrays, the size of each array is determined by `size`. The last chunk may contain less than size elements.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom[int]([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})

	// Chunk splits an array into multiple arrays,
	// the size of each array is determined by `size`.
	// The last chunk may contain less than size elements.
	fmt.Println(array.Chunk(2))

}
Output:
[[1 2] [3 4] [5 6] [7 8] [9]]

func (*ArrayList[T]) Clear

func (a *ArrayList[T]) Clear()

Clear deletes all items of current array.

func (*ArrayList[T]) Clone

func (a *ArrayList[T]) Clone() (newArray Collection[T])

Clone returns a new array, which is a copy of current array.

func (*ArrayList[T]) Contains

func (a *ArrayList[T]) Contains(value T) bool

Contains checks whether a value exists in the array.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	var array g.ArrayList[string]
	array.Add("a")
	fmt.Println(array.Contains("a"))
	fmt.Println(array.Contains("A"))
	fmt.Println(array.ContainsI("A"))

}
Output:
true
false
true

func (*ArrayList[T]) ContainsAll

func (a *ArrayList[T]) ContainsAll(values Collection[T]) bool

ContainsAll checks whether a value exists in the array.

func (*ArrayList[T]) ContainsI

func (a *ArrayList[T]) ContainsI(value T) bool

ContainsI checks whether a value exists in the array with case-insensitively. Note that it internally iterates the whole array to do the comparison with case-insensitively.

func (*ArrayList[T]) CountValues

func (a *ArrayList[T]) CountValues() map[any]int

CountValues counts the number of occurrences of all values in the array.

func (*ArrayList[T]) DeepCopy

func (a *ArrayList[T]) DeepCopy() Collection[T]

DeepCopy implements interface for deep copy of current type.

func (*ArrayList[T]) Equals

func (a *ArrayList[T]) Equals(another Collection[T]) bool

func (*ArrayList[T]) Fill

func (a *ArrayList[T]) Fill(startIndex int, num int, value T) error

Fill fills an array with num entries of the value `value`, keys starting at the `startIndex` parameter.

func (*ArrayList[T]) Filter

func (a *ArrayList[T]) Filter(filter func(index int, value T) bool) List[T]

Filter iterates array and filters elements using custom callback function. It removes the element from array if callback function `filter` returns true, it or else does nothing and continues iterating.

Example
array1 := g.NewArrayListFrom[*exampleElement]([]*exampleElement{
	{Code: 0},
	{Code: 1},
	{Code: 2},
	nil,
	{Message: "john"},
})
array2 := g.NewArrayListFrom[*exampleElement]([]*exampleElement{
	{Code: 0},
	{Code: 1},
	{Code: 2},
	nil,
	{Message: "john"},
})
fmt.Println(array1.Filter(func(index int, value *exampleElement) bool {
	return empty.IsNil(value)
}).Slice())
fmt.Println(array2.Filter(func(index int, value *exampleElement) bool {
	return empty.IsEmpty(value)
}).Slice())
Output:
[ 1 2 "john"]
[1 2 "john"]

func (*ArrayList[T]) FilterEmpty

func (a *ArrayList[T]) FilterEmpty() List[T]

FilterEmpty removes all empty value of the array. Values like: 0, nil, false, "", len(slice/map/chan) == 0 are considered empty.

Example
array1 := g.NewArrayListFrom[*exampleElement]([]*exampleElement{
	{Code: 0},
	{Code: 1},
	{Code: 2},
	nil,
	{Message: "john"},
})
array2 := g.NewArrayListFrom[*exampleElement]([]*exampleElement{
	{Code: 0},
	{Code: 1},
	{Code: 2},
	nil,
	{Message: "john"},
})
fmt.Printf("%v\n", array1.FilterNil().Slice())
fmt.Printf("%v\n", array2.FilterEmpty().Slice())
Output:
[ 1 2 "john"]
[1 2 "john"]

func (*ArrayList[T]) FilterNil

func (a *ArrayList[T]) FilterNil() List[T]

FilterNil removes all nil value of the array.

Example
array1 := g.NewArrayListFrom[*exampleElement]([]*exampleElement{
	{Code: 0},
	{Code: 1},
	{Code: 2},
	nil,
	{Message: "john"},
})
array2 := g.NewArrayListFrom[*exampleElement]([]*exampleElement{
	{Code: 0},
	{Code: 1},
	{Code: 2},
	nil,
	{Message: "john"},
})
fmt.Println(array1.FilterNil().Slice())
fmt.Println(array2.FilterEmpty().Slice())
Output:
[ 1 2 "john"]
[1 2 "john"]

func (*ArrayList[T]) ForEach

func (a *ArrayList[T]) ForEach(f func(value T) bool)

ForEach iterates all elements in this collection readonly with custom callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom[string]([]string{"a", "b", "c"})
	// ForEach is alias of ForEachAsc, which iterates the array readonly in ascending order
	//  with given callback function `f`.
	// If `f` returns true, then it continues iterating; or false to stop.
	array.ForEachAsc(func(k int, v string) bool {
		fmt.Println(k, v)
		return true
	})
	// ForEachDesc iterates the array readonly in descending order with given callback function `f`.
	// If `f` returns true, then it continues iterating; or false to stop.
	array.ForEachDesc(func(k int, v string) bool {
		fmt.Println(k, v)
		return true
	})

}
Output:
0 a
1 b
2 c
2 c
1 b
0 a

func (*ArrayList[T]) ForEachAsc

func (a *ArrayList[T]) ForEachAsc(f func(index int, value T) bool)

ForEachAsc iterates the array readonly in ascending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

func (*ArrayList[T]) ForEachDesc

func (a *ArrayList[T]) ForEachDesc(f func(k int, v T) bool)

ForEachDesc iterates the array readonly in descending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

func (*ArrayList[T]) Get

func (a *ArrayList[T]) Get(index int) (value T, found bool)

Get returns the value by the specified index. If the given `index` is out of range of the array, the `found` is false.

func (*ArrayList[T]) InsertAfter

func (a *ArrayList[T]) InsertAfter(index int, values ...T) error

InsertAfter inserts the `values` to the back of `index`.

func (*ArrayList[T]) InsertBefore

func (a *ArrayList[T]) InsertBefore(index int, values ...T) error

InsertBefore inserts the `values` to the front of `index`.

func (*ArrayList[T]) Interfaces

func (a *ArrayList[T]) Interfaces() []T

Interfaces returns current array as []T.

func (*ArrayList[T]) IsEmpty

func (a *ArrayList[T]) IsEmpty() bool

IsEmpty checks whether the array is empty.

func (*ArrayList[T]) Join

func (a *ArrayList[T]) Join(glue string) string

Join joins array elements with a string `glue`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom[string]([]string{"a", "b", "c", "d"})
	fmt.Println(array.Join(","))

}
Output:
a,b,c,d

func (*ArrayList[T]) Len

func (a *ArrayList[T]) Len() int

Len returns the length of array.

func (*ArrayList[T]) LockFunc

func (a *ArrayList[T]) LockFunc(f func(array []T))

LockFunc locks writing by callback function `f`.

func (ArrayList[T]) MarshalJSON

func (a ArrayList[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements the interface MarshalJSON for json.Marshal. Note that do not use pointer as its receiver here.

func (*ArrayList[T]) MustGet

func (a *ArrayList[T]) MustGet(index int) (value T)

MustGet returns the value by the specified index. If the given `index` is out of range of the array, it returns empty value of type T.

func (*ArrayList[T]) Pad

func (a *ArrayList[T]) Pad(size int, val T) List[T]

Pad pads array to the specified length with `value`. If size is positive then the array is padded on the right, or negative on the left. If the absolute value of `size` is less than or equal to the length of the array then no padding takes place.

func (*ArrayList[T]) PopLeft

func (a *ArrayList[T]) PopLeft() (value T, found bool)

PopLeft pops and returns an item from the beginning of array. Note that if the array is empty, the `found` is false.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})

	// Any MustPop* functions pick, delete and return the item from array.

	fmt.Println(array.PopLeft())
	fmt.Println(array.PopLefts(2))
	fmt.Println(array.PopRight())
	fmt.Println(array.PopRights(2))

}
Output:
1 true
[2 3]
9 true
[7 8]

func (*ArrayList[T]) PopLefts

func (a *ArrayList[T]) PopLefts(size int) []T

PopLefts pops and returns `size` items from the beginning of array.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})

	// Any MustPop* functions pick, delete and return the item from array.

	fmt.Println(array.PopLeft())
	fmt.Println(array.PopLefts(2))
	fmt.Println(array.PopRight())
	fmt.Println(array.PopRights(2))

}
Output:
1 true
[2 3]
9 true
[7 8]

func (*ArrayList[T]) PopRand

func (a *ArrayList[T]) PopRand() (value T, found bool)

PopRand randomly pops and return an item out of array. Note that if the array is empty, the `found` is false.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom[int]([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})

	// Randomly retrieve and return 2 items from the array.
	// It does not delete the items from array.
	fmt.Println(array.Rands(2))

	// Randomly pick and return one item from the array.
	// It deletes the picked up item from array.
	fmt.Println(array.PopRand())
}

func (*ArrayList[T]) PopRands

func (a *ArrayList[T]) PopRands(size int) []T

PopRands randomly pops and returns `size` items out of array.

func (*ArrayList[T]) PopRight

func (a *ArrayList[T]) PopRight() (value T, found bool)

PopRight pops and returns an item from the end of array. Note that if the array is empty, the `found` is false.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})

	// Any MustPop* functions pick, delete and return the item from array.

	fmt.Println(array.PopLeft())
	fmt.Println(array.PopLefts(2))
	fmt.Println(array.PopRight())
	fmt.Println(array.PopRights(2))

}
Output:
1 true
[2 3]
9 true
[7 8]

func (*ArrayList[T]) PopRights

func (a *ArrayList[T]) PopRights(size int) []T

PopRights pops and returns `size` items from the end of array.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})

	// Any MustPop* functions pick, delete and return the item from array.

	fmt.Println(array.PopLeft())
	fmt.Println(array.PopLefts(2))
	fmt.Println(array.PopRight())
	fmt.Println(array.PopRights(2))

}
Output:
1 true
[2 3]
9 true
[7 8]

func (*ArrayList[T]) PushLeft

func (a *ArrayList[T]) PushLeft(value ...T) List[T]

PushLeft pushes one or multiple items to the beginning of array.

func (*ArrayList[T]) PushRight

func (a *ArrayList[T]) PushRight(value ...T) List[T]

PushRight pushes one or multiple items to the end of array. It equals to Append.

func (*ArrayList[T]) RLockFunc

func (a *ArrayList[T]) RLockFunc(f func(array []T))

RLockFunc locks reading by callback function `f`.

func (*ArrayList[T]) Rand

func (a *ArrayList[T]) Rand() (value T, found bool)

Rand randomly returns one item from array(no deleting).

func (*ArrayList[T]) Rands

func (a *ArrayList[T]) Rands(size int) []T

Rands randomly returns `size` items from array(no deleting).

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom[int]([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})

	// Randomly retrieve and return 2 items from the array.
	// It does not delete the items from array.
	fmt.Println(array.Rands(2))

	// Randomly pick and return one item from the array.
	// It deletes the picked up item from array.
	fmt.Println(array.PopRand())
}

func (*ArrayList[T]) Range

func (a *ArrayList[T]) Range(start int, end ...int) []T

Range picks and returns items by range, like array[start:end]. Notice, if in concurrent-safe usage, it returns a copy of slice; else a pointer to the underlying data.

If `end` is negative, then the offset will start from the end of array. If `end` is omitted, then the sequence will have everything from start up until the end of the array.

func (*ArrayList[T]) Remove

func (a *ArrayList[T]) Remove(values ...T) bool

Remove removes multiple items by `values`.

func (*ArrayList[T]) RemoveAll

func (a *ArrayList[T]) RemoveAll(values Collection[T]) bool

RemoveAll removes multiple items by `values`.

func (*ArrayList[T]) RemoveAt

func (a *ArrayList[T]) RemoveAt(index int) (value T, found bool)

RemoveAt removes an item by index. If the given `index` is out of range of the array, the `found` is false.

func (*ArrayList[T]) RemoveValue

func (a *ArrayList[T]) RemoveValue(value T) bool

RemoveValue removes an item by value. It returns true if value is found in the array, or else false if not found.

func (*ArrayList[T]) Reverse

func (a *ArrayList[T]) Reverse() List[T]

Reverse makes array with elements in reverse order.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom[int]([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})

	// Reverse makes array with elements in reverse order.
	fmt.Println(array.Reverse().Slice())

}
Output:
[9 8 7 6 5 4 3 2 1]

func (*ArrayList[T]) Search

func (a *ArrayList[T]) Search(value T) int

Search searches array by `value`, returns the index of `value`, or returns -1 if not exists.

func (*ArrayList[T]) Set

func (a *ArrayList[T]) Set(index int, value T) error

Set sets value to specified index.

func (*ArrayList[T]) Shuffle

func (a *ArrayList[T]) Shuffle() List[T]

Shuffle randomly shuffles the array.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	array := g.NewArrayListFrom[int]([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})

	// Shuffle randomly shuffles the array.
	fmt.Println(array.Shuffle().Slice())
}

func (*ArrayList[T]) Size

func (a *ArrayList[T]) Size() int

Size returns the length of array.

func (*ArrayList[T]) Slice

func (a *ArrayList[T]) Slice() []T

Slice returns the underlying data of array. Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, or else a pointer to the underlying data.

func (*ArrayList[T]) Sort added in v0.9.2

func (a *ArrayList[T]) Sort(less func(v1, v2 T) bool)

Sort sorts the array by custom function `less`.

func (*ArrayList[T]) String

func (a *ArrayList[T]) String() string

String returns current array as a string, which implements like json.Marshal does.

func (*ArrayList[T]) SubSlice

func (a *ArrayList[T]) SubSlice(offset int, length ...int) []T

SubSlice returns a slice of elements from the array as specified by the `offset` and `size` parameters. If in concurrent safe usage, it returns a copy of the slice; else a pointer.

If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.

If length is given and is positive, then the sequence will have up to that many elements in it. If the array is shorter than the length, then only the available array elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.

Any possibility crossing the left border of array, it will fail.

func (*ArrayList[T]) Sum

func (a *ArrayList[T]) Sum() (sum int)

Sum returns the sum of values in an array.

func (*ArrayList[T]) Unique

func (a *ArrayList[T]) Unique() List[T]

Unique uniques the array, clear repeated items. Example: [1,1,2,3,2] -> [1,2,3]

func (*ArrayList[T]) UnmarshalJSON

func (a *ArrayList[T]) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

func (*ArrayList[T]) UnmarshalValue

func (a *ArrayList[T]) UnmarshalValue(value interface{}) error

UnmarshalValue is an interface implement which sets any type of value for array.

func (*ArrayList[T]) Values added in v0.9.12

func (a *ArrayList[T]) Values() []T

Values returns all elements of the array as a slice, maintaining the order of elements in the array. This method is functionally identical to Slice() and is provided for consistency with Map interfaces.

func (*ArrayList[T]) Walk

func (a *ArrayList[T]) Walk(f func(value T) T) List[T]

Walk applies a user supplied function `f` to every item of array.

type BTree

type BTree[K comparable, V comparable] struct {
	// contains filtered or unexported fields
}

BTree holds elements of the B-tree.

func NewBTree

func NewBTree[K comparable, V comparable](m int, comparator func(v1, v2 K) int, safe ...bool) *BTree[K, V]

NewBTree instantiates a B-tree with `m` (maximum number of children) and a custom key comparators. The parameter `safe` is used to specify whether using tree in concurrent-safety, which is false in default. Note that the `m` must be greater or equal than 3, or else it panics.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	bTree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		bTree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}
	fmt.Println(bTree.Map())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]

func NewBTreeFrom

func NewBTreeFrom[K comparable, V comparable](m int, comparator func(v1, v2 K) int, data map[K]V, safe ...bool) *BTree[K, V]

NewBTreeFrom instantiates a B-tree with `m` (maximum number of children), a custom key comparators and data map. The parameter `safe` is used to specify whether using tree in concurrent-safety, which is false in default.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	bTree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		bTree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	otherBTree := g.NewBTreeFrom(3, comparators.ComparatorString, bTree.Map())
	fmt.Println(otherBTree.Map())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]

func (*BTree[K, V]) Clear

func (tree *BTree[K, V]) Clear()

Clear removes all nodes from the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[int, string](3, comparators.ComparatorInt)
	for i := 0; i < 6; i++ {
		tree.Put(1000+i, "val"+gconv.String(i))
	}
	fmt.Println(tree.Size())

	tree.Clear()
	fmt.Println(tree.Size())

}
Output:
6
0

func (*BTree[K, V]) Clone

func (tree *BTree[K, V]) Clone(safe ...bool) Map[K, V]

Clone returns a new tree with a copy of current tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	b := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		b.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	tree := b.Clone()

	fmt.Println(tree.Map())
	fmt.Println(tree.Size())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]
6

func (*BTree[K, V]) ContainsKey

func (tree *BTree[K, V]) ContainsKey(key K) bool

ContainsKey checks whether `key` exists in the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.ContainsKey("key1"))
	fmt.Println(tree.ContainsKey("key6"))

}
Output:
true
false

func (*BTree[K, V]) ForEach

func (tree *BTree[K, V]) ForEach(f func(key K, value V) bool)

ForEach is alias of ForEachAsc.

Example

改为 ForEach/ForEachAsc/ForEachDesc

package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewBTree[int, int](3, comparators.ComparatorInt)
	for i := 0; i < 10; i++ {
		tree.Put(i, 10-i)
	}

	var totalKey, totalValue int
	tree.ForEach(func(key, value int) bool {
		totalKey += key
		totalValue += value

		return totalValue < 20
	})

	fmt.Println("totalKey:", totalKey)
	fmt.Println("totalValue:", totalValue)

}
Output:
totalKey: 3
totalValue: 27

func (*BTree[K, V]) ForEachAsc

func (tree *BTree[K, V]) ForEachAsc(f func(key K, value V) bool)

ForEachAsc iterates the tree readonly in ascending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewBTree[int, int](3, comparators.ComparatorInt)
	for i := 0; i < 10; i++ {
		tree.Put(i, 10-i)
	}

	tree.ForEachAsc(func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 0 , value: 10
key: 1 , value: 9
key: 2 , value: 8
key: 3 , value: 7
key: 4 , value: 6
key: 5 , value: 5
key: 6 , value: 4
key: 7 , value: 3
key: 8 , value: 2
key: 9 , value: 1

func (*BTree[K, V]) ForEachDesc

func (tree *BTree[K, V]) ForEachDesc(f func(key K, value V) bool)

ForEachDesc iterates the tree readonly in descending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewBTree[int, int](3, comparators.ComparatorInt)
	for i := 0; i < 10; i++ {
		tree.Put(i, 10-i)
	}

	tree.ForEachDesc(func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 9 , value: 1
key: 8 , value: 2
key: 7 , value: 3
key: 6 , value: 4
key: 5 , value: 5
key: 4 , value: 6
key: 3 , value: 7
key: 2 , value: 8
key: 1 , value: 9
key: 0 , value: 10

func (*BTree[K, V]) Get

func (tree *BTree[K, V]) Get(key K) (value V)

Get returns the value by given `key`, or empty value of type K if the key is not found in the map.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Get("key1"))
	fmt.Println(tree.Get("key10"))

}
Output:
val1

func (*BTree[K, V]) GetOrPut

func (tree *BTree[K, V]) GetOrPut(key K, value V) V

GetOrPut returns the value by key, or sets value with given `value` if it does not exist and then returns this value.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.GetOrPut("key1", "newVal1"))
	fmt.Println(tree.GetOrPut("key6", "val6"))

}
Output:
val1
val6

func (*BTree[K, V]) GetOrPutFunc

func (tree *BTree[K, V]) GetOrPutFunc(key K, f func() V) V

GetOrPutFunc returns the value by key, or sets value with returned value of callback function `f` if it does not exist and then returns this value.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.GetOrPutFunc("key1", func() string {
		return "newVal1"
	}))
	fmt.Println(tree.GetOrPutFunc("key6", func() string {
		return "val6"
	}))

}
Output:
val1
val6

func (*BTree[K, V]) Height

func (tree *BTree[K, V]) Height() int

Height returns the height of the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewBTree[int, int](3, comparators.ComparatorInt)
	for i := 0; i < 100; i++ {
		tree.Put(i, i)
	}
	fmt.Println(tree.Height())

}
Output:
6

func (*BTree[K, V]) IsEmpty

func (tree *BTree[K, V]) IsEmpty() bool

IsEmpty returns true if tree does not contain any nodes

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)

	fmt.Println(tree.IsEmpty())

	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.IsEmpty())

}
Output:
true
false

func (*BTree[K, V]) IteratorAscFrom

func (tree *BTree[K, V]) IteratorAscFrom(key K, match bool, f func(key K, value V) bool)

IteratorAscFrom iterates the tree readonly in ascending order with given callback function `f`. The parameter `key` specifies the start entry for iterating. The `match` specifies whether starting iterating if the `key` is fully matched, or else using index searching iterating. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		m[i] = i * 10
	}
	tree := g.NewBTreeFrom(3, comparators.ComparatorInt, m)

	tree.IteratorAscFrom(1, true, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 1 , value: 10
key: 2 , value: 20
key: 3 , value: 30
key: 4 , value: 40
key: 5 , value: 50

func (*BTree[K, V]) IteratorDescFrom

func (tree *BTree[K, V]) IteratorDescFrom(key K, match bool, f func(key K, value V) bool)

IteratorDescFrom iterates the tree readonly in descending order with given callback function `f`. The parameter `key` specifies the start entry for iterating. The `match` specifies whether starting iterating if the `key` is fully matched, or else using index searching iterating. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		m[i] = i * 10
	}
	tree := g.NewBTreeFrom(3, comparators.ComparatorInt, m)

	tree.IteratorDescFrom(5, true, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 5 , value: 50
key: 4 , value: 40
key: 3 , value: 30
key: 2 , value: 20
key: 1 , value: 10

func (*BTree[K, V]) IteratorFrom

func (tree *BTree[K, V]) IteratorFrom(key K, match bool, f func(key K, value V) bool)

IteratorFrom is alias of IteratorAscFrom.

func (*BTree[K, V]) KeySet added in v0.9.10

func (tree *BTree[K, V]) KeySet() Set[K]

KeySet returns a set of the keys contained in the tree.

func (*BTree[K, V]) Keys

func (tree *BTree[K, V]) Keys() []K

Keys returns all keys in asc order.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 6; i > 0; i-- {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Keys())

}
Output:
[key1 key2 key3 key4 key5 key6]

func (*BTree[K, V]) Left

func (tree *BTree[K, V]) Left() *BTreeEntry[K, V]

Left returns the left-most (min) entry or nil if tree is empty.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewBTree[int, int](3, comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		tree.Put(i, i)
	}
	fmt.Println(tree.Left().Key(), tree.Left().Value())

	emptyTree := g.NewBTree[int, int](3, comparators.ComparatorInt)
	fmt.Println(emptyTree.Left())

}
Output:
1 1
<nil>

func (*BTree[K, V]) Map

func (tree *BTree[K, V]) Map() map[K]V

Map returns all key-value items as map.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Map())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]

func (*BTree[K, V]) MapStrAny

func (tree *BTree[K, V]) MapStrAny() map[string]V

MapStrAny returns all key-value items as map[string]V.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[int, string](3, comparators.ComparatorInt)
	for i := 0; i < 6; i++ {
		tree.Put(1000+i, "val"+gconv.String(i))
	}

	fmt.Println(tree.MapStrAny())

}
Output:
map[1000:val0 1001:val1 1002:val2 1003:val3 1004:val4 1005:val5]

func (BTree[K, V]) MarshalJSON

func (tree BTree[K, V]) MarshalJSON() (jsonBytes []byte, err error)

MarshalJSON implements the interface MarshalJSON for json.Marshal.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/internal/json"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	bytes, err := json.Marshal(tree)
	if err == nil {
		fmt.Println(gconv.String(bytes))
	}

}
Output:
{"key0":"val0","key1":"val1","key2":"val2","key3":"val3","key4":"val4","key5":"val5"}

func (*BTree[K, V]) Print

func (tree *BTree[K, V]) Print()

Print prints the tree to stdout.

Example
package main

import (
	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	tree.Print()

}
Output:
key0
key1
    key2
key3
    key4
    key5

func (*BTree[K, V]) Put

func (tree *BTree[K, V]) Put(key K, value V)

Put inserts key-value item into the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Map())
	fmt.Println(tree.Size())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]
6

func (*BTree[K, V]) PutIfAbsent

func (tree *BTree[K, V]) PutIfAbsent(key K, value V) bool

PutIfAbsent sets `value` to the map if the `key` does not exist, and then returns true. It returns false if `key` exists, and `value` would be ignored.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.PutIfAbsent("key1", "newVal1"))
	fmt.Println(tree.PutIfAbsent("key6", "val6"))

}
Output:
false
true

func (*BTree[K, V]) PutIfAbsentFunc

func (tree *BTree[K, V]) PutIfAbsentFunc(key K, f func() V) bool

PutIfAbsentFunc sets value with return value of callback function `f`, and then returns true. It returns false if `key` exists, and `value` would be ignored.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.PutIfAbsentFunc("key1", func() string {
		return "newVal1"
	}))
	fmt.Println(tree.PutIfAbsentFunc("key6", func() string {
		return "val6"
	}))

}
Output:
false
true

func (*BTree[K, V]) Puts

func (tree *BTree[K, V]) Puts(data map[K]V)

Puts batch sets key-values to the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)

	tree.Puts(map[string]string{
		"key1": "val1",
		"key2": "val2",
	})

	fmt.Println(tree.Map())
	fmt.Println(tree.Size())

}
Output:
map[key1:val1 key2:val2]
2

func (*BTree[K, V]) Remove

func (tree *BTree[K, V]) Remove(key K) (value V, removed bool)

Remove removes the node from the tree by `key`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Remove("key1"))
	fmt.Println(tree.Remove("key6"))
	fmt.Println(tree.Map())

}
Output:
val1 true
 false
map[key0:val0 key2:val2 key3:val3 key4:val4 key5:val5]

func (*BTree[K, V]) Removes

func (tree *BTree[K, V]) Removes(keys []K)

Removes batch deletes values of the tree by `keys`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	removeKeys := make([]string, 2)
	removeKeys = append(removeKeys, "key1")
	removeKeys = append(removeKeys, "key6")

	tree.Removes(removeKeys)

	fmt.Println(tree.Map())

}
Output:
map[key0:val0 key2:val2 key3:val3 key4:val4 key5:val5]

func (*BTree[K, V]) Replace

func (tree *BTree[K, V]) Replace(data map[K]V)

Replace the data of the tree with given `data`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Map())

	data := map[string]string{
		"newKey0": "newVal0",
		"newKey1": "newVal1",
		"newKey2": "newVal2",
	}

	tree.Replace(data)

	fmt.Println(tree.Map())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]
map[newKey0:newVal0 newKey1:newVal1 newKey2:newVal2]

func (*BTree[K, V]) Right

func (tree *BTree[K, V]) Right() *BTreeEntry[K, V]

Right returns the right-most (max) entry or nil if tree is empty.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewBTree[int, int](3, comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		tree.Put(i, i)
	}
	fmt.Println(tree.Right().Key(), tree.Right().Value())

	emptyTree := g.NewBTree[int, int](3, comparators.ComparatorInt)
	fmt.Println(emptyTree.Left())

}
Output:
99 99
<nil>

func (*BTree[K, V]) Search

func (tree *BTree[K, V]) Search(key K) (value V, found bool)

Search searches the tree with given `key`. Second return parameter `found` is true if key was found, otherwise false.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Search("key0"))
	fmt.Println(tree.Search("key6"))

}
Output:
val0 true
 false

func (*BTree[K, V]) Size

func (tree *BTree[K, V]) Size() int

Size returns number of nodes in the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)

	fmt.Println(tree.Size())

	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Size())

}
Output:
0
6

func (*BTree[K, V]) String

func (tree *BTree[K, V]) String() string

String returns a string representation of container (for debugging purposes)

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree)

}
Output:
key0
key1
    key2
key3
    key4
    key5

func (*BTree[K, V]) Values

func (tree *BTree[K, V]) Values() []V

Values returns all values in asc order based on the key.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewBTree[string, string](3, comparators.ComparatorString)
	for i := 6; i > 0; i-- {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Values())

}
Output:
[val1 val2 val3 val4 val5 val6]

type BTreeEntry

type BTreeEntry[K comparable, V comparable] struct {
	// contains filtered or unexported fields
}

BTreeEntry represents the key-value pair contained within nodes.

func (*BTreeEntry[K, V]) Key

func (n *BTreeEntry[K, V]) Key() K

func (*BTreeEntry[K, V]) Value

func (n *BTreeEntry[K, V]) Value() V

type BTreeNode

type BTreeNode[K comparable, V comparable] struct {
	Parent   *BTreeNode[K, V]
	Entries  []*BTreeEntry[K, V] // Contained keys in node
	Children []*BTreeNode[K, V]  // Children nodes
}

BTreeNode is a single element within the tree.

type Collection

type Collection[T any] interface {
	// Add adds all the elements in the specified slice to this collection.
	// Returns true if this collection changed as a result of the call
	Add(...T) bool

	// AddAll adds all the elements in the specified collection to this collection.
	// Returns true if this collection changed as a result of the call
	AddAll(Collection[T]) bool

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

	// Clone returns a new collection, which is a copy of current collection.
	Clone() Collection[T]

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

	// ContainsAll returns true if this collection contains all the elements in the specified collection.
	ContainsAll(Collection[T]) bool

	// DeepCopy implements interface for deep copy of current type.
	DeepCopy() Collection[T]

	// Equals compares the specified object with this collection for equality.
	Equals(another Collection[T]) bool

	// ForEach iterates all elements in this collection readonly with custom callback function `f`.
	// If `f` returns true, then it continues iterating; or false to stop.
	ForEach(func(T) bool)

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

	// Join joins array elements with a string `glue`.
	Join(glue string) string

	// Remove removes all of this collection's elements that are also contained in the specified slice
	// if it is present.
	// Returns true if this collection changed as a result of the call
	Remove(...T) bool

	// RemoveAll removes all of this collection's elements that are also contained in the specified collection
	// Returns true if this collection changed as a result of the call
	RemoveAll(Collection[T]) bool

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

	// Slice returns an array containing shadow copy of all the elements in this collection.
	Slice() []T

	// Values returns all elements of the set as a slice, maintaining the order of elements in the set.
	// This method is functionally identical to Slice() and is provided for consistency with Map interfaces.
	Values() []T

	// String returns items as a string, which implements like json.Marshal does.
	String() string
}

Collection is the root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered.

type Element

type Element[T any] struct {

	// The value stored with this element.
	Value T
	// contains filtered or unexported fields
}

Element is an element of a linked list.

func (*Element[T]) Next

func (e *Element[T]) Next() *Element[T]

Next returns the next list element or nil.

func (*Element[T]) Prev

func (e *Element[T]) Prev() *Element[T]

Prev returns the previous list element or nil.

type HashMap

type HashMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

HashMap wraps map type `map[K]V` and provides more map features.

func NewHashMap

func NewHashMap[K comparable, V any](safe ...bool) *HashMap[K, V]

NewHashMap creates and returns an empty hash map. The parameter `safe` is used to specify whether using map in concurrent-safety, which is false in default.

func NewHashMapFrom

func NewHashMapFrom[K comparable, V any](data map[K]V, safe ...bool) *HashMap[K, V]

NewHashMapFrom creates and returns a hash map from given map `data`. Note that, the param `data` map will be set as the underlying data map(no deep copy), there might be some concurrent-safe issues when changing the map outside. The parameter `safe` is used to specify whether using tree in concurrent-safety, which is false in default.

func (*HashMap[K, V]) Clear

func (m *HashMap[K, V]) Clear()

Clear deletes all data of the map, it will remake a new underlying data map.

func (*HashMap[K, V]) Clone

func (m *HashMap[K, V]) Clone(safe ...bool) Map[K, V]

Clone returns a new hash map with copy of current map data.

func (*HashMap[K, V]) ContainsKey

func (m *HashMap[K, V]) ContainsKey(key K) bool

ContainsKey checks whether a key exists. It returns true if the `key` exists, or else false.

func (*HashMap[K, V]) DeepCopy

func (m *HashMap[K, V]) DeepCopy() interface{}

DeepCopy implements interface for deep copy of current type.

func (*HashMap[K, V]) FilterEmpty

func (m *HashMap[K, V]) FilterEmpty()

FilterEmpty deletes all key-value pair of which the value is empty. Values like: 0, nil, false, "", len(slice/map/chan) == 0 are considered empty.

func (*HashMap[K, V]) FilterNil

func (m *HashMap[K, V]) FilterNil()

FilterNil deletes all key-value pair of which the value is nil.

func (*HashMap[K, V]) ForEach

func (m *HashMap[K, V]) ForEach(f func(k K, v V) bool)

ForEach iterates the hash map readonly with custom callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

func (*HashMap[K, V]) Get

func (m *HashMap[K, V]) Get(key K) (value V)

Get returns the value by given `key`, or empty value of type K if the key is not found in the map.

func (*HashMap[K, V]) GetOrPut

func (m *HashMap[K, V]) GetOrPut(key K, value V) V

GetOrPut returns the value by key, or sets value with given `value` if it does not exist and then returns this value.

func (*HashMap[K, V]) GetOrPutFunc

func (m *HashMap[K, V]) GetOrPutFunc(key K, f func() V) V

GetOrPutFunc returns the value by key, or sets value with returned value of callback function `f` if it does not exist and then returns this value.

func (*HashMap[K, V]) IsEmpty

func (m *HashMap[K, V]) IsEmpty() bool

IsEmpty checks whether the map is empty. It returns true if map is empty, or else false.

func (*HashMap[K, V]) KeySet added in v0.9.10

func (m *HashMap[K, V]) KeySet() Set[K]

KeySet returns a set of the keys contained in the map.

func (*HashMap[K, V]) Keys

func (m *HashMap[K, V]) Keys() []K

Keys returns all keys of the map as a slice.

func (*HashMap[K, V]) LockFunc

func (m *HashMap[K, V]) LockFunc(f func(m map[K]V))

LockFunc locks writing with given callback function `f` within RWMutex.Lock.

func (*HashMap[K, V]) Map

func (m *HashMap[K, V]) Map() map[K]V

Map returns a shallow copy of the underlying data of the hash map.

func (*HashMap[K, V]) MapStrAny

func (m *HashMap[K, V]) MapStrAny() map[string]V

MapStrAny returns a copy of the underlying data of the map as map[string]any.

func (HashMap[K, V]) MarshalJSON

func (m HashMap[K, V]) MarshalJSON() ([]byte, error)

MarshalJSON implements the interface MarshalJSON for json.Marshal.

func (*HashMap[K, V]) Merge

func (m *HashMap[K, V]) Merge(other *HashMap[K, V])

Merge merges two hash maps. The `other` map will be merged into the map `m`.

func (*HashMap[K, V]) Pop

func (m *HashMap[K, V]) Pop() (key K, value V)

Pop retrieves and deletes an item from the map.

func (*HashMap[K, V]) Pops

func (m *HashMap[K, V]) Pops(size int) map[K]V

Pops retrieves and deletes `size` items from the map. It returns all items if size == -1.

func (*HashMap[K, V]) Put

func (m *HashMap[K, V]) Put(key K, value V)

Put sets key-value to the hash map.

func (*HashMap[K, V]) PutIfAbsent

func (m *HashMap[K, V]) PutIfAbsent(key K, value V) bool

PutIfAbsent sets `value` to the map if the `key` does not exist, and then returns true. It returns false if `key` exists, and `value` would be ignored.

func (*HashMap[K, V]) PutIfAbsentFunc

func (m *HashMap[K, V]) PutIfAbsentFunc(key K, f func() V) bool

PutIfAbsentFunc sets value with return value of callback function `f`, and then returns true. It returns false if `key` exists, and `value` would be ignored.

func (*HashMap[K, V]) Puts

func (m *HashMap[K, V]) Puts(data map[K]V)

Puts batch sets key-values to the hash map.

func (*HashMap[K, V]) RLockFunc

func (m *HashMap[K, V]) RLockFunc(f func(m map[K]V))

RLockFunc locks reading with given callback function `f` within RWMutex.RLock.

func (*HashMap[K, V]) Remove

func (m *HashMap[K, V]) Remove(key K) (value V, removed bool)

Remove deletes value from map by given `key`, and return this deleted value.

func (*HashMap[K, V]) Removes

func (m *HashMap[K, V]) Removes(keys []K)

Removes batch deletes values of the map by keys.

func (*HashMap[K, V]) Replace

func (m *HashMap[K, V]) Replace(data map[K]V)

Replace the data of the map with given `data`.

func (*HashMap[K, V]) Search

func (m *HashMap[K, V]) Search(key K) (value V, found bool)

Search searches the map with given `key`. Second return parameter `found` is true if key was found, otherwise false.

func (*HashMap[K, V]) Size

func (m *HashMap[K, V]) Size() int

Size returns the size of the map.

func (*HashMap[K, V]) String

func (m *HashMap[K, V]) String() string

String returns the map as a string.

func (*HashMap[K, V]) UnmarshalJSON

func (m *HashMap[K, V]) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

func (*HashMap[K, V]) UnmarshalValue

func (m *HashMap[K, V]) UnmarshalValue(value interface{}) (err error)

UnmarshalValue is an interface implement which sets any type of value for map.

func (*HashMap[K, V]) Values

func (m *HashMap[K, V]) Values() []V

Values returns all values of the map as a slice.

func (*HashMap[K, V]) Walk

func (m *HashMap[K, V]) Walk(other *HashMap[K, V])

type HashSet

type HashSet[T comparable] struct {
	// contains filtered or unexported fields
}

HashSet implements the Set interface, backed by a golang map instance. It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This struct permits the nil or empty element.

func NewHashSet

func NewHashSet[T comparable](safe ...bool) *HashSet[T]

NewHashSet create and returns a new set, which contains un-repeated items. Also see NewArrayList.

func NewHashSetFrom

func NewHashSetFrom[T comparable](items []T, safe ...bool) *HashSet[T]

NewHashSetFrom returns a new set from `items`. Parameter `items` can be either a variable of any type, or a slice.

func (*HashSet[T]) Add

func (set *HashSet[T]) Add(items ...T) bool

Add adds one or multiple items to the set.

func (*HashSet[T]) AddAll

func (set *HashSet[T]) AddAll(items Collection[T]) bool

AddAll adds all the elements in the specified collection to this set.

func (*HashSet[T]) Clear

func (set *HashSet[T]) Clear()

Clear deletes all items of the set.

func (*HashSet[T]) Clone

func (set *HashSet[T]) Clone() Collection[T]

func (*HashSet[T]) Complement

func (set *HashSet[T]) Complement(full Set[T]) (newSet Set[T])

Complement returns a new set which is the complement from `set` to `full`. Which means, all the items in `newSet` are in `full` and not in `set`.

It returns the difference between `full` and `set` if the given set `full` is not the full set of `set`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	s1 := g.NewHashSetFrom([]int{1, 2, 3})
	s2 := g.NewHashSetFrom([]int{4, 5, 6})
	s3 := g.NewHashSetFrom([]int{1, 2, 3, 4, 5, 6, 7})

	fmt.Println(s3.Intersect(s1).Slice())
	fmt.Println(s3.Diff(s1).Slice())
	fmt.Println(s1.Union(s2).Slice())
	fmt.Println(s1.Complement(s3).Slice())

	// May Output:
	// [2 3 1]
	// [5 6 7 4]
	// [6 1 2 3 4 5]
	// [4 5 6 7]
}

func (*HashSet[T]) Contains

func (set *HashSet[T]) Contains(item T) bool

Contains checks whether the set contains `item`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	var set g.HashSet[string]
	set.Add("a")
	fmt.Println(set.Contains("a"))
	fmt.Println(set.Contains("A"))
	fmt.Println(set.ContainsI("A"))

}
Output:
true
false
true

func (*HashSet[T]) ContainsAll

func (set *HashSet[T]) ContainsAll(items Collection[T]) bool

ContainsAll returns true if this collection contains all the elements in the specified collection.

func (*HashSet[T]) ContainsI

func (set *HashSet[T]) ContainsI(item T) bool

ContainsI checks whether a value exists in the set with case-insensitively. Note that it internally iterates the whole set to do the comparison with case-insensitively.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	var set g.HashSet[string]
	set.Add("a")
	fmt.Println(set.Contains("a"))
	fmt.Println(set.Contains("A"))
	fmt.Println(set.ContainsI("A"))

}
Output:
true
false
true

func (*HashSet[T]) DeepCopy

func (set *HashSet[T]) DeepCopy() Collection[T]

DeepCopy implements interface for deep copy of current type.

func (*HashSet[T]) Diff

func (set *HashSet[T]) Diff(others ...Set[T]) (newSet Set[T])

Diff returns a new set which is the difference set from `set` to `others`. Which means, all the items in `newSet` are in `set` but not in any of the `others`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	s1 := g.NewHashSetFrom([]int{1, 2, 3})
	s2 := g.NewHashSetFrom([]int{4, 5, 6})
	s3 := g.NewHashSetFrom([]int{1, 2, 3, 4, 5, 6, 7})

	fmt.Println(s3.Intersect(s1).Slice())
	fmt.Println(s3.Diff(s1).Slice())
	fmt.Println(s1.Union(s2).Slice())
	fmt.Println(s1.Complement(s3).Slice())

	// May Output:
	// [2 3 1]
	// [5 6 7 4]
	// [6 1 2 3 4 5]
	// [4 5 6 7]
}

func (*HashSet[T]) Equals

func (set *HashSet[T]) Equals(another Collection[T]) bool

Equals checks whether the two sets equal.

func (*HashSet[T]) ForEach

func (set *HashSet[T]) ForEach(f func(v T) bool)

ForEach iterates the set readonly with given callback function `f`, if `f` returns true then continue iterating; or false to stop.

func (*HashSet[T]) Intersect

func (set *HashSet[T]) Intersect(others ...Set[T]) (newSet Set[T])

Intersect returns a new set which is the intersection from `set` to `others`. Which means, all the items in `newSet` are in `set` and also in all the `others`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	s1 := g.NewHashSetFrom[int]([]int{1, 2, 3})
	s2 := g.NewHashSetFrom[int]([]int{4, 5, 6})
	s3 := g.NewHashSetFrom[int]([]int{1, 2, 3, 4, 5, 6, 7})

	fmt.Println(s3.Intersect(s1).Slice())
	fmt.Println(s3.Diff(s1).Slice())
	fmt.Println(s1.Union(s2).Slice())
	fmt.Println(s1.Complement(s3).Slice())

	// May Output:
	// [2 3 1]
	// [5 6 7 4]
	// [6 1 2 3 4 5]
	// [4 5 6 7]
}

func (*HashSet[T]) IsDisjointWith added in v0.9.11

func (set *HashSet[T]) IsDisjointWith(other Set[T]) bool

IsDisjointWith returns true if the current set has no elements in common with the given set.

func (*HashSet[T]) IsEmpty

func (set *HashSet[T]) IsEmpty() bool

IsEmpty returns true if this collection contains no elements.

func (*HashSet[T]) IsSubsetOf

func (set *HashSet[T]) IsSubsetOf(other Set[T]) bool

IsSubsetOf checks whether the current set is a sub-set of `other`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	var s1, s2 g.HashSet[int]
	s1.Add([]int{1, 2, 3}...)
	s2.Add([]int{2, 3}...)
	fmt.Println(s1.IsSubsetOf(&s2))
	fmt.Println(s2.IsSubsetOf(&s1))

}
Output:
false
true

func (*HashSet[T]) IsSupersetOf added in v0.9.11

func (set *HashSet[T]) IsSupersetOf(other Set[T]) bool

IsSupersetOf checks whether the current set is a super-set of `other`.

func (*HashSet[T]) Join

func (set *HashSet[T]) Join(glue string) string

Join joins items with a string `glue`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	var set g.HashSet[string]
	set.Add("a", "b", "c", "d")
	fmt.Println(set.Join(","))

	// May Output:
	// a,b,c,d
}

func (*HashSet[T]) LockFunc

func (set *HashSet[T]) LockFunc(f func(m map[T]struct{}))

LockFunc locks writing with callback function `f`.

func (HashSet[T]) MarshalJSON

func (set HashSet[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements the interface MarshalJSON for json.Marshal.

func (*HashSet[T]) Merge

func (set *HashSet[T]) Merge(others ...Set[T]) Set[T]

Merge adds items from `others` sets into `set`.

func (*HashSet[T]) Permutation added in v0.9.12

func (set *HashSet[T]) Permutation() [][]T

Permutation returns all possible permutations of the set elements. A permutation is a rearrangement of the elements. For a set with n elements, there are n! (n factorial) permutations. Returns a slice of slices, where each inner slice represents one permutation.

Example
// Create a new HashSet with some elements
set := NewHashSetFrom([]int{1, 2, 3})

// Get all permutations
permutations := set.Permutation()

// Sort the set elements for consistent output
elements := set.Slice()
sort.Ints(elements)

fmt.Printf("Set: %v\n", elements)
fmt.Printf("Number of permutations: %d\n", len(permutations))
fmt.Println("All permutations:")

// Sort permutations for consistent output
sort.Slice(permutations, func(i, j int) bool {
	for k := 0; k < len(permutations[i]); k++ {
		if k >= len(permutations[j]) {
			return false
		}
		if permutations[i][k] != permutations[j][k] {
			return permutations[i][k] < permutations[j][k]
		}
	}
	return len(permutations[i]) < len(permutations[j])
})

for i, perm := range permutations {
	fmt.Printf("  %d: %v\n", i+1, perm)
}
Output:
Set: [1 2 3]
Number of permutations: 6
All permutations:
  1: [1 2 3]
  2: [1 3 2]
  3: [2 1 3]
  4: [2 3 1]
  5: [3 1 2]
  6: [3 2 1]

func (*HashSet[T]) Pop

func (set *HashSet[T]) Pop() (value T)

Pop randomly pops an item from set.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	var set g.HashSet[int]
	set.Add(1, 2, 3, 4)
	fmt.Println(set.Pop())
	fmt.Println(set.Pops(2))
	fmt.Println(set.Size())

	// May Output:
	// 1
	// [2 3]
	// 1
}

func (*HashSet[T]) Pops

func (set *HashSet[T]) Pops(size int) []T

Pops randomly pops `size` items from set. It returns all items if size == -1.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	var set g.HashSet[int]
	set.Add(1, 2, 3, 4)
	fmt.Println(set.Pop())
	fmt.Println(set.Pops(2))
	fmt.Println(set.Size())

	// May Output:
	// 1
	// [2 3]
	// 1
}

func (*HashSet[T]) RLockFunc

func (set *HashSet[T]) RLockFunc(f func(m map[T]struct{}))

RLockFunc locks reading with callback function `f`.

func (*HashSet[T]) Remove

func (set *HashSet[T]) Remove(items ...T) bool

Remove deletes `items` from set.

func (*HashSet[T]) RemoveAll

func (set *HashSet[T]) RemoveAll(items Collection[T]) bool

RemoveAll removes all of this collection's elements that are also contained in the specified collection

func (*HashSet[T]) Size

func (set *HashSet[T]) Size() int

Size returns the size of the set.

func (*HashSet[T]) Slice

func (set *HashSet[T]) Slice() []T

Slice returns the an of items of the set as slice.

func (*HashSet[T]) String

func (set *HashSet[T]) String() string

String returns items as a string, which implements like json.Marshal does.

func (*HashSet[T]) Sum

func (set *HashSet[T]) Sum() (sum int)

Sum sums items. Note: The items should be converted to int type, or you'd get a result that you unexpected.

func (*HashSet[T]) Union

func (set *HashSet[T]) Union(others ...Set[T]) (newSet Set[T])

Union returns a new set which is the union of `set` and `others`. Which means, all the items in `newSet` are in `set` or in `others`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	s1 := g.NewHashSetFrom([]int{1, 2, 3})
	s2 := g.NewHashSetFrom([]int{4, 5, 6})
	s3 := g.NewHashSetFrom([]int{1, 2, 3, 4, 5, 6, 7})

	fmt.Println(s3.Intersect(s1).Slice())
	fmt.Println(s3.Diff(s1).Slice())
	fmt.Println(s1.Union(s2).Slice())
	fmt.Println(s1.Complement(s3).Slice())

	// May Output:
	// [2 3 1]
	// [5 6 7 4]
	// [6 1 2 3 4 5]
	// [4 5 6 7]
}

func (*HashSet[T]) UnmarshalJSON

func (set *HashSet[T]) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

Example

UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/internal/json"
)

func main() {
	b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`)
	type Student struct {
		Id     int
		Name   string
		Scores *g.HashSet[int]
	}
	s := Student{}
	_ = json.Unmarshal(b, &s)
	fmt.Println(s)

	// May Output:
	// {1 john [100,99,98]}
}

func (*HashSet[T]) UnmarshalValue

func (set *HashSet[T]) UnmarshalValue(value interface{}) (err error)

UnmarshalValue is an interface implement which sets any type of value for set.

Example

UnmarshalValue is an interface implement which sets any type of value for set.

package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/internal/json"
)

func main() {
	b := []byte(`{"Id":1,"Name":"john","Scores":100,99,98}`)
	type Student struct {
		Id     int
		Name   string
		Scores *g.HashSet[int]
	}
	s := Student{}
	_ = json.Unmarshal(b, &s)
	fmt.Println(s)

	// May Output:
	// {1 john [100,99,98]}
}

func (*HashSet[T]) Values added in v0.9.12

func (set *HashSet[T]) Values() []T

Values returns all elements of the set as a slice, maintaining the order of elements in the set. This method is functionally identical to Slice() and is provided for consistency with Map interfaces.

func (*HashSet[T]) Walk

func (set *HashSet[T]) Walk(f func(item T) T) *HashSet[T]

Walk applies a user supplied function `f` to every item of set.

Example

Walk applies a user supplied function `f` to every item of set.

package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	var (
		set   g.HashSet[int]
		names = []int{1, 0}
		delta = 10
	)
	set.Add(names...)
	// Add prefix for given table names.
	set.Walk(func(item int) int {
		return delta + item
	})
	fmt.Println(set.Slice())

	// May Output:
	// [12 60]
}

type LinkedHashMap

type LinkedHashMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

LinkedHashMap is a map that preserves insertion-order.

It is backed by a hash table to store values and doubly-linked list to store ordering.

Structure is not thread safe.

Reference: http://en.wikipedia.org/wiki/Associative_array

func NewListMap

func NewListMap[K comparable, V any](safe ...bool) *LinkedHashMap[K, V]

NewListMap returns an empty link map. LinkedHashMap is backed by a hash table to store values and doubly-linked list to store ordering. The parameter `safe` is used to specify whether using map in concurrent-safety, which is false in default.

func NewListMapFrom

func NewListMapFrom[K comparable, V any](data map[K]V, safe ...bool) *LinkedHashMap[K, V]

NewListMapFrom returns a link map from given map `data`. Note that, the param `data` map will be set as the underlying data map(no deep copy), there might be some concurrent-safe issues when changing the map outside.

func (*LinkedHashMap[K, V]) Clear

func (m *LinkedHashMap[K, V]) Clear()

Clear deletes all data of the map, it will remake a new underlying data map.

func (*LinkedHashMap[K, V]) Clone

func (m *LinkedHashMap[K, V]) Clone(safe ...bool) Map[K, V]

Clone returns a new link map with copy of current map data.

func (*LinkedHashMap[K, V]) ContainsKey

func (m *LinkedHashMap[K, V]) ContainsKey(key K) (ok bool)

ContainsKey checks whether a key exists. It returns true if the `key` exists, or else false.

func (*LinkedHashMap[K, V]) DeepCopy

func (m *LinkedHashMap[K, V]) DeepCopy() interface{}

DeepCopy implements interface for deep copy of current type.

func (*LinkedHashMap[K, V]) FilterEmpty

func (m *LinkedHashMap[K, V]) FilterEmpty()

FilterEmpty deletes all key-value pair of which the value is empty.

func (*LinkedHashMap[K, V]) ForEach

func (m *LinkedHashMap[K, V]) ForEach(f func(key K, value V) bool)

ForEach is alias of ForEachAsc.

func (*LinkedHashMap[K, V]) ForEachAsc

func (m *LinkedHashMap[K, V]) ForEachAsc(f func(key K, value V) bool)

ForEachAsc iterates the map readonly in ascending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

func (*LinkedHashMap[K, V]) ForEachDesc

func (m *LinkedHashMap[K, V]) ForEachDesc(f func(key K, value interface{}) bool)

ForEachDesc iterates the map readonly in descending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

func (*LinkedHashMap[K, V]) Get

func (m *LinkedHashMap[K, V]) Get(key K) (value V)

Get returns the value by given `key`, or empty value of type K if the key is not found in the map.

func (*LinkedHashMap[K, V]) GetOrPut

func (m *LinkedHashMap[K, V]) GetOrPut(key K, value V) V

GetOrPut returns the value by key, or sets value with given `value` if it does not exist and then returns this value.

func (*LinkedHashMap[K, V]) GetOrPutFunc

func (m *LinkedHashMap[K, V]) GetOrPutFunc(key K, f func() V) V

GetOrPutFunc returns the value by key, or sets value with returned value of callback function `f` if it does not exist and then returns this value.

GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` with mutex.Lock of the map.

func (*LinkedHashMap[K, V]) IsEmpty

func (m *LinkedHashMap[K, V]) IsEmpty() bool

IsEmpty checks whether the map is empty. It returns true if map is empty, or else false.

func (*LinkedHashMap[K, V]) KeySet added in v0.9.10

func (m *LinkedHashMap[K, V]) KeySet() Set[K]

KeySet returns a set of the keys contained in the map.

func (*LinkedHashMap[K, V]) Keys

func (m *LinkedHashMap[K, V]) Keys() []K

Keys returns all keys of the map as a slice in ascending order.

func (*LinkedHashMap[K, V]) Map

func (m *LinkedHashMap[K, V]) Map() map[K]V

Map returns a copy of the underlying data of the map.

func (*LinkedHashMap[K, V]) MapStrAny

func (m *LinkedHashMap[K, V]) MapStrAny() map[string]V

MapStrAny returns a copy of the underlying data of the map as map[string]V.

func (LinkedHashMap[K, V]) MarshalJSON

func (m LinkedHashMap[K, V]) MarshalJSON() (jsonBytes []byte, err error)

MarshalJSON implements the interface MarshalJSON for json.Marshal.

func (*LinkedHashMap[K, V]) Merge

func (m *LinkedHashMap[K, V]) Merge(other *LinkedHashMap[K, V])

Merge merges two link maps. The `other` map will be merged into the map `m`.

func (*LinkedHashMap[K, V]) Pop

func (m *LinkedHashMap[K, V]) Pop() (key K, value V)

Pop retrieves and deletes an item from the map.

func (*LinkedHashMap[K, V]) Pops

func (m *LinkedHashMap[K, V]) Pops(size int) map[K]V

Pops retrieves and deletes `size` items from the map. It returns all items if size == -1.

func (*LinkedHashMap[K, V]) Put

func (m *LinkedHashMap[K, V]) Put(key K, value V)

Put sets key-value to the map.

func (*LinkedHashMap[K, V]) PutIfAbsent

func (m *LinkedHashMap[K, V]) PutIfAbsent(key K, value V) bool

PutIfAbsent sets `value` to the map if the `key` does not exist, and then returns true. It returns false if `key` exists, and `value` would be ignored.

func (*LinkedHashMap[K, V]) PutIfAbsentFunc

func (m *LinkedHashMap[K, V]) PutIfAbsentFunc(key K, f func() V) bool

PutIfAbsentFunc sets value with return value of callback function `f`, and then returns true. It returns false if `key` exists, and `value` would be ignored.

func (*LinkedHashMap[K, V]) Puts

func (m *LinkedHashMap[K, V]) Puts(data map[K]V)

Puts batch sets key-values to the map.

func (*LinkedHashMap[K, V]) Remove

func (m *LinkedHashMap[K, V]) Remove(key K) (value V, removed bool)

Remove deletes value from map by given `key`, and return this deleted value.

func (*LinkedHashMap[K, V]) Removes

func (m *LinkedHashMap[K, V]) Removes(keys []K)

Removes batch deletes values of the map by keys.

func (*LinkedHashMap[K, V]) Replace

func (m *LinkedHashMap[K, V]) Replace(data map[K]V)

Replace the data of the map with given `data`.

func (*LinkedHashMap[K, V]) Search

func (m *LinkedHashMap[K, V]) Search(key K) (value V, found bool)

Search searches the map with given `key`. Second return parameter `found` is true if key was found, otherwise false.

func (*LinkedHashMap[K, V]) Size

func (m *LinkedHashMap[K, V]) Size() (size int)

Size returns the size of the map.

func (*LinkedHashMap[K, V]) String

func (m *LinkedHashMap[K, V]) String() string

String returns the map as a string.

func (*LinkedHashMap[K, V]) UnmarshalJSON

func (m *LinkedHashMap[K, V]) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

func (*LinkedHashMap[K, V]) UnmarshalValue

func (m *LinkedHashMap[K, V]) UnmarshalValue(value interface{}) (err error)

UnmarshalValue is an interface implement which sets any type of value for map.

func (*LinkedHashMap[K, V]) Values

func (m *LinkedHashMap[K, V]) Values() []V

Values returns all values of the map as a slice.

type LinkedList

type LinkedList[T any] struct {
	// contains filtered or unexported fields
}

LinkedList represents a doubly linked list. The zero value for LinkedList is an empty list ready to use.

func NewLinkedList

func NewLinkedList[T any](safe ...bool) *LinkedList[T]

NewLinkedList returns an initialized list.

func NewLinkedListFrom

func NewLinkedListFrom[T any](array []T, safe ...bool) *LinkedList[T]

NewLinkedListFrom creates and returns a list from a copy of given slice `array`. The parameter `safe` is used to specify whether using list in concurrent-safety, which is false in default.

func (*LinkedList[T]) Add

func (l *LinkedList[T]) Add(values ...T) bool

Add append a new element e with value v at the back of list l and returns true.

func (*LinkedList[T]) AddAll

func (l *LinkedList[T]) AddAll(values Collection[T]) bool

AddAll adds all the elements in the specified collection to this list. Returns true if this collection changed as a result of the call

func (*LinkedList[T]) Back

func (l *LinkedList[T]) Back() *Element[T]

Back returns the last element of list l or nil if the list is empty.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Back().Value)
	fmt.Println(l)

	e := l.Back()
	l.InsertBefore(e, 9)
	l.InsertAfter(e, 6)

	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
[1,2,3,4,9,5,6]

func (*LinkedList[T]) BackAll

func (l *LinkedList[T]) BackAll() (values []T)

BackAll copies and returns values of all elements from back of `l` as slice.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l)
	fmt.Println(l.BackAll())

}
Output:
[1,2,3,4,5]
[5 4 3 2 1]

func (*LinkedList[T]) BackValue

func (l *LinkedList[T]) BackValue() (value T)

BackValue returns value of the last element of `l` or nil if the list is empty.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l)
	fmt.Println(l.BackValue())

}
Output:
[1,2,3,4,5]
5

func (*LinkedList[T]) Clear

func (l *LinkedList[T]) Clear()

Clear removes all the elements from this collection.

func (*LinkedList[T]) Clone

func (l *LinkedList[T]) Clone() Collection[T]

func (*LinkedList[T]) Contains

func (l *LinkedList[T]) Contains(value T) bool

Contains returns true if this collection contains the specified element.

func (*LinkedList[T]) ContainsAll

func (l *LinkedList[T]) ContainsAll(values Collection[T]) bool

ContainsAll returns true if this collection contains all the elements in the specified collection.

func (*LinkedList[T]) DeepCopy

func (l *LinkedList[T]) DeepCopy() Collection[T]

DeepCopy implements interface for deep copy of current type.

func (*LinkedList[T]) Equals

func (l *LinkedList[T]) Equals(another Collection[T]) bool

func (*LinkedList[T]) ForEach

func (l *LinkedList[T]) ForEach(f func(T) bool)

ForEach iterates all elements in this collection readonly with custom callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

func (*LinkedList[T]) ForEachAsc

func (l *LinkedList[T]) ForEachAsc(f func(e T) bool)

ForEachAsc iterates the list readonly in ascending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	// concurrent-safe list.
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 10, 1).Slice(), true)
	// iterate reading from head using ForEachAsc.
	l.ForEachAsc(func(e int) bool {
		fmt.Print(e)
		return true
	})

}
Output:
12345678910

func (*LinkedList[T]) ForEachDesc

func (l *LinkedList[T]) ForEachDesc(f func(e T) bool)

ForEachDesc iterates the list readonly in descending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	// concurrent-safe list.
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 10, 1).Slice(), true)
	// iterate reading from tail using ForEachDesc.
	l.ForEachDesc(func(e int) bool {
		fmt.Print(e)
		return true
	})
}
Output:
10987654321

func (*LinkedList[T]) Front

func (l *LinkedList[T]) Front() *Element[T]

Front returns the first element of list l or nil if the list is empty.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Front().Value)
	fmt.Println(l)

	e := l.Front()
	l.InsertBefore(e, 0)
	l.InsertAfter(e, 9)

	fmt.Println(l)

}
Output:
1
[1,2,3,4,5]
[0,1,9,2,3,4,5]

func (*LinkedList[T]) FrontAll

func (l *LinkedList[T]) FrontAll() (values []T)

FrontAll copies and returns values of all elements from front of `l` as slice.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l)
	fmt.Println(l.FrontAll())

}
Output:
[1,2,3,4,5]
[1 2 3 4 5]

func (*LinkedList[T]) FrontValue

func (l *LinkedList[T]) FrontValue() (value T)

FrontValue returns value of the first element of `l` or nil if the list is empty.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l)
	fmt.Println(l.FrontValue())

}
Output:
[1,2,3,4,5]
1

func (*LinkedList[T]) Init

func (l *LinkedList[T]) Init() *LinkedList[T]

Init initializes or clears list l.

func (*LinkedList[T]) InsertAfter

func (l *LinkedList[T]) InsertAfter(mark *Element[T], v T) *Element[T]

InsertAfter inserts a new element e with value v immediately after mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)

	l.InsertAfter(l.Front(), 8)
	l.InsertAfter(l.Back(), 9)

	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
7
[1,8,2,3,4,5,9]

func (*LinkedList[T]) InsertBefore

func (l *LinkedList[T]) InsertBefore(mark *Element[T], v T) *Element[T]

InsertBefore inserts a new element e with value v immediately before mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)

	l.InsertBefore(l.Front(), 8)
	l.InsertBefore(l.Back(), 9)

	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
7
[8,1,2,3,4,9,5]

func (*LinkedList[T]) IsEmpty

func (l *LinkedList[T]) IsEmpty() bool

IsEmpty returns true if this collection contains no elements.

func (*LinkedList[T]) Join

func (l *LinkedList[T]) Join(glue string) string

Join joins list elements with a string `glue`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	var l g.LinkedList[string]
	l.PushBacks([]string{"a", "b", "c", "d"})

	fmt.Println(l.Join(","))

}
Output:
a,b,c,d

func (*LinkedList[T]) Len

func (l *LinkedList[T]) Len() int

Len returns the number of elements of list l. The complexity is O(1).

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int]([]int{1, 2, 3, 4, 5})

	fmt.Println(l.Len())

}
Output:
5

func (LinkedList[T]) MarshalJSON

func (l LinkedList[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements the interface MarshalJSON for json.Marshal.

func (*LinkedList[T]) MoveAfter

func (l *LinkedList[T]) MoveAfter(e, mark *Element[T])

MoveAfter moves element e to its new position after mark. If e or mark is not an element of l, or e == mark, the list is not modified. The element and mark must not be nil.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Size())
	fmt.Println(l)

	// element of `l`
	e := l.PushFront(0)
	fmt.Println(l.Size())
	fmt.Println(l)

	l.MoveAfter(e, l.Back())

	fmt.Println(l.Size())
	fmt.Println(l)

	// not element of `l`
	e = &g.Element[int]{Value: -1}
	l.MoveAfter(e, l.Back())

	fmt.Println(l.Size())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
6
[0,1,2,3,4,5]
6
[1,2,3,4,5,0]
6
[1,2,3,4,5,0]

func (*LinkedList[T]) MoveBefore

func (l *LinkedList[T]) MoveBefore(e, mark *Element[T])

MoveBefore moves element e to its new position before mark. If e or mark is not an element of l, or e == mark, the list is not modified. The element and mark must not be nil.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Size())
	fmt.Println(l)

	// element of `l`
	e := l.PushBack(6)
	fmt.Println(l.Size())
	fmt.Println(l)

	l.MoveBefore(e, l.Front())

	fmt.Println(l.Size())
	fmt.Println(l)

	// not element of `l`
	e = &g.Element[int]{Value: 7}
	l.MoveBefore(e, l.Front())

	fmt.Println(l.Size())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
6
[1,2,3,4,5,6]
6
[6,1,2,3,4,5]
6
[6,1,2,3,4,5]

func (*LinkedList[T]) MoveToBack

func (l *LinkedList[T]) MoveToBack(e *Element[T])

MoveToBack moves element e to the back of list l. If e is not an element of l, the list is not modified. The element must not be nil.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Size())
	fmt.Println(l)

	// element of `l`
	l.MoveToBack(l.Front())

	fmt.Println(l.Size())
	fmt.Println(l)

	// not element of `l`
	e := &g.Element[int]{Value: 0}
	l.MoveToBack(e)

	fmt.Println(l.Size())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
5
[2,3,4,5,1]
5
[2,3,4,5,1]

func (*LinkedList[T]) MoveToFront

func (l *LinkedList[T]) MoveToFront(e *Element[T])

MoveToFront moves element e to the front of list l. If e is not an element of l, the list is not modified. The element must not be nil.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Size())
	fmt.Println(l)

	// element of `l`
	l.MoveToFront(l.Back())

	fmt.Println(l.Size())
	fmt.Println(l)

	// not element of `l`
	e := &g.Element[int]{Value: 6}
	l.MoveToFront(e)

	fmt.Println(l.Size())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
5
[5,1,2,3,4]
5
[5,1,2,3,4]

func (*LinkedList[T]) PopBack

func (l *LinkedList[T]) PopBack() (value T, ok bool)

PopBack removes the element from back of `l` and returns the value of the element.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)
	v, _ := l.PopBack()
	fmt.Println(v)
	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
5
4
[1,2,3,4]

func (*LinkedList[T]) PopBackAll

func (l *LinkedList[T]) PopBackAll() []T

PopBackAll removes all elements from back of `l` and returns values of the removed elements as slice.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)
	fmt.Println(l.PopBackAll())
	fmt.Println(l.Len())

}
Output:
5
[1,2,3,4,5]
[5 4 3 2 1]
0

func (*LinkedList[T]) PopBacks

func (l *LinkedList[T]) PopBacks(max int) (values []T)

PopBacks removes `max` elements from back of `l` and returns values of the removed elements as slice.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)
	fmt.Println(l.PopBacks(2))
	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
[5 4]
3
[1,2,3]

func (*LinkedList[T]) PopFront

func (l *LinkedList[T]) PopFront() (value T, ok bool)

PopFront removes the element from front of `l` and returns the value of the element.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)
	v, _ := l.PopFront()
	fmt.Println(v)
	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
1
4
[2,3,4,5]

func (*LinkedList[T]) PopFrontAll

func (l *LinkedList[T]) PopFrontAll() []T

PopFrontAll removes all elements from front of `l` and returns values of the removed elements as slice.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)
	fmt.Println(l.PopFrontAll())
	fmt.Println(l.Len())

}
Output:
5
[1,2,3,4,5]
[1 2 3 4 5]
0

func (*LinkedList[T]) PopFronts

func (l *LinkedList[T]) PopFronts(max int) (values []T)

PopFronts removes `max` elements from front of `l` and returns values of the removed elements as slice.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)
	fmt.Println(l.PopFronts(2))
	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
[1 2]
3
[3,4,5]

func (*LinkedList[T]) PushBack

func (l *LinkedList[T]) PushBack(v T) *Element[T]

PushBack inserts a new element e with value v at the back of list l and returns e.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)

	l.PushBack(6)

	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
6
[1,2,3,4,5,6]

func (*LinkedList[T]) PushBackList

func (l *LinkedList[T]) PushBackList(other *LinkedList[T])

PushBackList inserts a copy of another list at the back of list l. The lists l and other may be the same. They must not be nil.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Size())
	fmt.Println(l)

	other := g.NewLinkedListFrom[int]([]int{6, 7, 8, 9, 10})

	fmt.Println(other.Size())
	fmt.Println(other)

	l.PushBackList(other)

	fmt.Println(l.Size())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
5
[6,7,8,9,10]
10
[1,2,3,4,5,6,7,8,9,10]

func (*LinkedList[T]) PushBacks

func (l *LinkedList[T]) PushBacks(values []T)

PushBacks inserts multiple new elements with values `values` at the back of list `l`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)

	l.PushBacks([]int{6, 7, 8, 9, 10})

	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
10
[1,2,3,4,5,6,7,8,9,10]

func (*LinkedList[T]) PushFront

func (l *LinkedList[T]) PushFront(v T) *Element[T]

PushFront inserts a new element e with value v at the front of list l and returns e.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)

	l.PushFront(0)

	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
6
[0,1,2,3,4,5]

func (*LinkedList[T]) PushFrontList

func (l *LinkedList[T]) PushFrontList(other *LinkedList[T])

PushFrontList inserts a copy of another list at the front of list l. The lists l and other may be the same. They must not be nil.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Size())
	fmt.Println(l)

	other := g.NewLinkedListFrom[int]([]int{-4, -3, -2, -1, 0})

	fmt.Println(other.Size())
	fmt.Println(other)

	l.PushFrontList(other)

	fmt.Println(l.Size())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
5
[-4,-3,-2,-1,0]
10
[-4,-3,-2,-1,0,1,2,3,4,5]

func (*LinkedList[T]) PushFronts

func (l *LinkedList[T]) PushFronts(values []T)

PushFronts inserts multiple new elements with values `values` at the front of list `l`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)

	l.PushFronts([]int{0, -1, -2, -3, -4})

	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
10
[-4,-3,-2,-1,0,1,2,3,4,5]

func (*LinkedList[T]) Remove

func (l *LinkedList[T]) Remove(values ...T) (changed bool)

Remove removes all of this list's elements that are also contained in the specified slice if it is present. Returns true if this collection changed as a result of the call

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)

	fmt.Println(l.Remove(l.Front().Value))
	fmt.Println(l.Remove(l.Back().Value))

	fmt.Println(l.Len())
	fmt.Println(l)

	fmt.Println(l.Remove(l.Front().Value, l.Back().Value))

	fmt.Println(l.Len())
	fmt.Println(l)

}
Output:
5
[1,2,3,4,5]
true
true
3
[2,3,4]
true
1
[3]

func (*LinkedList[T]) RemoveAll

func (l *LinkedList[T]) RemoveAll(values Collection[T]) (changed bool)

RemoveAll removes all of this list's elements that are also contained in the specified collection Returns true if this collection changed as a result of the call

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int](g.NewArrayListRange(1, 5, 1).Slice())

	fmt.Println(l.Len())
	fmt.Println(l)

	l.Clear()

	fmt.Println(l.Len())

}
Output:
5
[1,2,3,4,5]
0

func (*LinkedList[T]) Size

func (l *LinkedList[T]) Size() int

Size is alias of Len.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
)

func main() {
	l := g.NewLinkedListFrom[int]([]int{1, 2, 3, 4, 5})

	fmt.Println(l.Size())

}
Output:
5

func (*LinkedList[T]) Slice

func (l *LinkedList[T]) Slice() []T

Slice returns an array containing shadow copy of all the elements in this list.

func (*LinkedList[T]) String

func (l *LinkedList[T]) String() string

String returns current list as a string.

func (*LinkedList[T]) Sum

func (l *LinkedList[T]) Sum() (sum int)

Sum returns the sum of values in an array.

func (*LinkedList[T]) UnmarshalJSON

func (l *LinkedList[T]) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

func (*LinkedList[T]) UnmarshalValue

func (l *LinkedList[T]) UnmarshalValue(value interface{}) (err error)

UnmarshalValue is an interface implement which sets any type of value for list.

func (*LinkedList[T]) Values added in v0.9.12

func (l *LinkedList[T]) Values() []T

Values returns all elements of the list as a slice, maintaining the order of elements in the list. This method is functionally identical to Slice() and is provided for consistency with Map interfaces.

type List

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

	// Chunk splits an array into multiple arrays,
	// the size of each array is determined by `size`.
	// The last chunk may contain less than size elements.
	Chunk(size int) [][]T

	// ContainsI checks whether a value exists in the array with case-insensitively, only applying to element type string
	// For element type other than string, ContainsI returns the same result as Contains
	// Note that it internally iterates the whole array to do the comparison with case-insensitively.
	ContainsI(value T) bool

	// ForEachAsc iterates the array readonly in ascending order with given callback function `f`.
	// If `f` returns true, then it continues iterating; or false to stop.
	ForEachAsc(f func(int, T) bool)

	// ForEachDesc iterates the array readonly in descending order with given callback function `f`.
	// If `f` returns true, then it continues iterating; or false to stop.
	ForEachDesc(f func(int, T) bool)

	// Filter iterates array and filters elements using custom callback function.
	// It removes the element from array if callback function `filter` returns true,
	// it or else does nothing and continues iterating.
	Filter(filter func(index int, value T) bool) List[T]

	// FilterNil removes all nil value of the array.
	FilterNil() List[T]

	// FilterEmpty removes all empty value of the array.
	// Values like: 0, nil, false, "", len(slice/map/chan) == 0 are considered empty.
	FilterEmpty() List[T]

	// Get returns the element at the specified position in this list.
	// If given `index` is out of range, returns empty `value` for type T and bool value false as `found`.
	Get(index int) (value T, found bool)

	// MustGet returns the element at the specified position in this list.
	// If given `index` is out of range, returns empty `value` for type T.
	MustGet(index int) (value T)

	// PopLeft pops and returns an item from the beginning of array.
	// Note that if the array is empty, the `found` is false.
	PopLeft() (value T, found bool)

	// PopLefts pops and returns `size` items from the beginning of array.
	PopLefts(size int) []T

	// PopRand randomly pops and return an item out of array.
	// Note that if the array is empty, the `found` is false.
	PopRand() (value T, found bool)

	// PopRands randomly pops and returns `size` items out of array.
	PopRands(size int) []T

	// PopRight pops and returns an item from the end of array.
	// Note that if the array is empty, the `found` is false.
	PopRight() (value T, found bool)

	// PopRights pops and returns `size` items from the end of array.
	PopRights(size int) []T

	// Rand randomly returns one item from array(no deleting).
	Rand() (value T, found bool)

	// Rands randomly returns `size` items from array(no deleting).
	Rands(size int) []T

	// Range picks and returns items by range, like array[start:end].
	// Notice, if in concurrent-safe usage, it returns a copy of slice;
	// else a pointer to the underlying data.
	//
	// If `end` is negative, then the offset will start from the end of array.
	// If `end` is omitted, then the sequence will have everything from start up
	// until the end of the array.
	Range(start int, end ...int) []T

	// RemoveAt removes an item by index.
	// If the given `index` is out of range of the array, the `found` is false.
	RemoveAt(index int) (value T, found bool)

	// Search searches array by `value`, returns the index of `value`,
	// or returns -1 if not exists.
	Search(value T) int

	// Set replaces the element at the specified position in this list with the specified element.
	Set(index int, value T) error

	// Sort sorts the array by custom function `less`.
	Sort(less func(v1, v2 T) bool)

	// SubSlice returns a slice of elements from the array as specified
	// by the `offset` and `size` parameters.
	// If in concurrent safe usage, it returns a copy of the slice; else a pointer.
	//
	// If offset is non-negative, the sequence will start at that offset in the array.
	// If offset is negative, the sequence will start that far from the end of the array.
	//
	// If length is given and is positive, then the sequence will have up to that many elements in it.
	// If the array is shorter than the length, then only the available array elements will be present.
	// If length is given and is negative then the sequence will stop that many elements from the end of the array.
	// If it is omitted, then the sequence will have everything from offset up until the end of the array.
	//
	// Any possibility crossing the left border of array, it will fail.
	SubSlice(offset int, length ...int) []T

	// Sum returns the sum of converted integer of each value in an array.
	// Note: converting value into integer may result in unpredictable problems
	Sum() (sum int)

	// Unique uniques the array, clear repeated items.
	// Example: [1,1,2,3,2] -> [1,2,3]
	Unique() List[T]

	// Walk applies a user supplied function `f` to every item of array.
	Walk(f func(value T) T) List[T]
}

List is nn ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

type Map

type Map[K comparable, V any] interface {
	// Put sets key-value to the map.
	Put(key K, value V)

	// Puts batch sets key-values to the map.
	Puts(data map[K]V)

	// PutIfAbsent sets `value` to the map if the `key` does not exist, and then returns true.
	// It returns false if `key` exists, and `value` would be ignored.
	PutIfAbsent(key K, value V) bool

	// PutIfAbsentFunc sets value with return value of callback function `f`, and then returns true.
	// It returns false if `key` exists, and `value` would be ignored.
	PutIfAbsentFunc(key K, f func() V) bool

	// Search searches the map with given `key`.
	// Second return parameter `found` is true if key was found, otherwise false.
	Search(key K) (value V, found bool)

	// Get returns the value by given `key`, or empty value of type V if key is not found in the map.
	Get(key K) (value V)

	// GetOrPut returns the value for the given key.
	// If the key is not found in the map, sets its value with given `value` and returns it.
	GetOrPut(key K, value V) V

	// GetOrPutFunc returns the value by key,
	// If the key is not found in the map, calls the f function, puts its result into the map under the given key and returns it.
	GetOrPutFunc(key K, f func() V) V

	// Remove removes the node from the tree by `key`.
	Remove(key K) (value V, removed bool)

	// Removes batch deletes values of the tree by `keys`.
	Removes(keys []K)

	// ForEach iterates all entries in the map readonly with custom callback function `f`.
	// If `f` returns true, then it continues iterating; or false to stop.
	ForEach(f func(key K, value V) bool)

	// ContainsKey checks whether `key` exists in the map.
	ContainsKey(key K) bool

	// Size returns the size of the map.
	Size() int

	// KeySet returns all keys of the map as a set.
	KeySet() Set[K]

	// Keys returns all keys of the map as a slice, maintaining the order of belonging entries in the map.
	Keys() []K

	// Values returns all values of the map as a slice, maintaining the order of belonging entries in the map.
	Values() []V

	// Map returns a shallow copy of the underlying data of the hash map.
	Map() map[K]V

	// MapStrAny returns a copy of the underlying data of the map as map[string]any.
	MapStrAny() map[string]V

	// IsEmpty checks whether the map is empty.
	// It returns true if map is empty, or else false.
	IsEmpty() bool

	// Clear deletes all data of the map, it will remake a new underlying data map.
	Clear()

	// Replace the data of the map with given `data`.
	Replace(data map[K]V)

	// Clone returns a new hash map with copy of current map data.
	Clone(safe ...bool) Map[K, V]

	// String returns the map as a string.
	String() string
}

Map defines common functions of a `map` and provides more map features. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap struct, make specific guarantees as to their order; others, like the HashMap struct, do not.

type MapEntry

type MapEntry[K comparable, V any] interface {
	// Key returns the key corresponding to this entry.
	Key() K

	// Value returns the value corresponding to this entry.
	Value() V
}

MapEntry is a key-value pair, usually representing the element entries in a Map

type RedBlackTreeNode

type RedBlackTreeNode[K comparable, V any] struct {
	// contains filtered or unexported fields
}

RedBlackTreeNode is a single element within the tree.

func (*RedBlackTreeNode[K, V]) Key

func (n *RedBlackTreeNode[K, V]) Key() K

func (*RedBlackTreeNode[K, V]) Value

func (n *RedBlackTreeNode[K, V]) Value() V

type Set

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

	// Diff returns a new set containing elements that are in the current set but not in any of the given sets.
	// This method does not modify the current set.
	// Example: {1,2,3}.Diff({2,3}) => {1}
	Diff(...Set[T]) Set[T]

	// Complement returns a new set containing elements that are in the given 'full' set but not in the current set.
	// This method does not modify the current set.
	// If the given set is the same as the current set, the result is an empty set.
	// Example: {1,2}.Complement({1,2,3,4}) => {3,4}
	Complement(Set[T]) Set[T]

	// Merge merges the given sets into the current set (in-place).
	// This method modifies the current set by adding all elements from the given sets.
	// Returns the current set after modification.
	// Note: Unlike Union, which returns a new set and does not modify the current set,
	// Merge performs in-place modification.
	Merge(...Set[T]) Set[T]

	// Intersect returns a new set containing elements that are present in the current set and in all of the given sets.
	// This method does not modify the current set.
	// Example: {1,2,3}.Intersect({2,3,4}) => {2,3}
	Intersect(...Set[T]) Set[T]

	// Union returns a new set containing all elements that are present in the current set or in any of the given sets.
	// This method does not modify the current set.
	// Example: {1,2}.Union({2,3}) => {1,2,3}
	Union(...Set[T]) Set[T]

	// IsSubsetOf returns true if the current set is a subset of the given set.
	// That is, every element of the current set is also in the given set.
	// Example: {1,2}.IsSubsetOf({1,2,3}) => true
	IsSubsetOf(Set[T]) bool

	// IsSupersetOf returns true if the current set is a superset of the given set.
	// That is, every element of the given set is also in the current set.
	// Example: {1,2,3}.IsSupersetOf({1,2}) => true
	IsSupersetOf(Set[T]) bool

	// IsDisjointWith returns true if the current set has no elements in common with the given set.
	// That is, the intersection of the two sets is empty.
	// Example: {1,2}.IsDisjointWith({3,4}) => true
	IsDisjointWith(Set[T]) bool

	// Permutation returns all possible permutations of the set elements.
	// A permutation is a rearrangement of the elements.
	// For a set with n elements, there are n! (n factorial) permutations.
	// Returns a slice of slices, where each inner slice represents one permutation.
	// Example: {1,2,3}.Permutation() => [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
	Permutation() [][]T
}

Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one nil element. As implied by its name, this interface models the mathematical set abstraction.

type SortedMap

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

	// AscendingKeySet returns a view of the keys contained in this map, in its natural ascending order.
	AscendingKeySet() SortedSet[K]

	// CeilingEntry returns a key-value mapping associated with the least key greater than or equal to the given key, or nil if there is no such key.
	CeilingEntry(key K) MapEntry[K, V]

	// CeilingKey returns the least key greater than or equal to the given key, or empty of type K if there is no such key.
	// The parameter `ok` indicates whether a non-empty `ceilingKey` is returned.
	CeilingKey(key K) (ceilingKey K, ok bool)

	// DescendingKeySet returns a reversed order view of the keys contained in this map.
	DescendingKeySet() SortedSet[K]

	// FirstEntry returns a key-value mapping associated with the least key in this map, or nil if the map is empty.
	FirstEntry() MapEntry[K, V]

	// FloorEntry returns a key-value mapping associated with the greatest key less than or equal to the given key, or nil if there is no such key.
	FloorEntry(key K) MapEntry[K, V]

	// FloorKey returns the greatest key less than or equal to the given key, or empty of type K if there is no such key.
	// The parameter `ok` indicates whether a non-empty `floorKey` is returned.
	FloorKey(key K) (floorKey K, ok bool)

	// HeadMap returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.
	HeadMap(toKey K, inclusive bool) SortedMap[K, V]

	// HigherEntry returns a key-value mapping associated with the least key strictly greater than the given key, or nil if there is no such key.
	HigherEntry(key K) MapEntry[K, V]

	// HigherKey returns the least key strictly greater than the given key, or empty of type K if there is no such key.
	// The parameter `ok` indicates whether a non-empty `higherKey` is returned.
	HigherKey(key K) (higherKey K, ok bool)

	// LastEntry returns a key-value mapping associated with the greatest key in this map, or nil if the map is empty.
	LastEntry() MapEntry[K, V]

	// LowerEntry returns a key-value mapping associated with the greatest key strictly less than the given key, or nil if there is no such key.
	LowerEntry(key K) MapEntry[K, V]

	// LowerKey returns the greatest key strictly less than the given key, or empty of type K if there is no such key.
	// The parameter `ok` indicates whether a non-empty `lowerKey` is returned.
	LowerKey(key K) (lowerKey K, ok bool)

	// PollFirstEntry removes and returns a key-value mapping associated with the least key in this map, or nil if the map is empty.
	PollFirstEntry() MapEntry[K, V]

	// PollLastEntry removes and returns a key-value mapping associated with the greatest key in this map, or nil if the map is empty.
	PollLastEntry() MapEntry[K, V]

	// Reverse returns a reverse order view of the mappings contained in this map.
	Reverse() SortedMap[K, V]

	// SubMap returns a view of the portion of this map whose keys range from fromKey to toKey.
	SubMap(fromKey K, fromInclusive bool, toKey K, toInclusive bool) SortedMap[K, V]

	// TailMap returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.
	TailMap(fromKey K, inclusive bool) SortedMap[K, V]
}

SortedMap is a Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySet, keySet and values methods). Several additional operations are provided to take advantage of the ordering.

(This interface is the map analogue of SortedSet.)

All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator).

SortedMap also provides navigation methods returning the closest matches for given search targets. Methods LowerEntry, FloorEntry, CeilingEntry, and HigherEntry return MapEntry associated with keys respectively less than, less than or equal, greater than or equal, and greater than a given key, returning empty if there is no such key. Similarly, methods LowerKey, FloorKey, CeilingKey, and HigherKey return only the associated keys. All of these methods are designed for locating, not traversing entries.

type SortedSet

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

	// Ceiling returns the least element in this set greater than or equal to the given `element` and true as `found`,
	// or empty of type T and false as `found` if there is no such element.
	Ceiling(element T) (ceiling T, found bool)

	// Comparator returns the comparators used to order the elements in this set,
	// or nil if this set uses the natural ordering of its elements.
	Comparator() comparators.Comparator[T]

	// First returns the first (lowest) element currently in this set.
	First() (element T, found bool)

	// Floor returns the greatest element in this set less than or equal to the given `element` and true as `found`,
	// or empty of type T and false as `found` if there is no such element.
	Floor(element T) (floor T, found bool)

	// ForEachDescending iterates the tree readonly in descending order with given callback function `f`.
	// If `f` returns true, then it continues iterating; or false to stop.
	ForEachDescending(func(T) bool)

	// HeadSet returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) toElement.
	HeadSet(toElement T, inclusive bool) SortedSet[T]

	// Higher returns the least element in this set strictly greater than the given `element` and true as `found`,
	// or empty of type T and false as `found` if there is no such element.
	Higher(element T) (higher T, found bool)

	// Last Returns the last (highest) element currently in this set.
	Last() (element T, found bool)

	// Lower returns the greatest element in this set strictly less than the given `element` and true as `found`,
	// or empty of type T and false as `found` if there is no such element.
	Lower(element T) (lower T, found bool)

	// PollFirst retrieves and removes the first (lowest) element and true as `found`,
	// or returns empty of type T and false as `found` if this set is empty.
	PollFirst() (first T, found bool)

	// PollHeadSet retrieves and removes portion of this set whose elements are less than
	// (or equal to, if inclusive is true) toElement.
	PollHeadSet(toElement T, inclusive bool) SortedSet[T]

	// PollLast retrieves and removes the last (highest) element and true as `found`,
	// or returns empty of type T and false as `found` if this set is empty.
	PollLast() (last T, found bool)

	// PollTailSet retrieves and removes portion of this set whose elements are greater than
	// (or equal to, if inclusive is true) fromElement.
	PollTailSet(fromElement T, inclusive bool) SortedSet[T]

	// SubSet returns a view of the portion of this set whose elements range from fromElement to toElement.
	SubSet(fromElement T, fromInclusive bool, toElement T, toInclusive bool) SortedSet[T]

	// TailSet returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.
	TailSet(fromElement T, inclusive bool) SortedSet[T]
}

SortedSet is a Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time. The set's iterator will traverse the set in ascending element order. Several additional operations are provided to take advantage of the ordering. (This interface is the set analogue of SortedMap.)

SortedSet inherits all methods from Set interface, including Permutation() which returns all possible permutations of the set elements in the order defined by the underlying implementation (typically based on the set's iteration order).

SortedSet also provides navigation methods lower, floor, ceiling, and higher return elements respectively less than, less than or equal, greater than or equal, and greater than a given element, returning empty if there is no such element.

type TreeMap

type TreeMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

TreeMap implements the red-black tree.

func NewTreeMap added in v0.9.7

func NewTreeMap[K comparable, V any](comparator comparators.Comparator[K], safe ...bool) *TreeMap[K, V]

NewTreeMap instantiates a red-black tree with the custom key comparators. The parameter `safe` is used to specify whether using tree in concurrent-safety, which is false in default.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}
	fmt.Println(tree)
}
Output:
│           ┌── key5
│       ┌── key4
│   ┌── key3
│   │   └── key2
└── key1
    └── key0

func NewTreeMapDefault added in v0.9.7

func NewTreeMapDefault[K comparable, V any](safe ...bool) *TreeMap[K, V]

NewTreeMapDefault instantiates a red-black tree with default key comparators. The parameter `safe` is used to specify whether using tree in concurrent-safety, which is false in default.

func NewTreeMapFrom added in v0.9.7

func NewTreeMapFrom[K comparable, V any](comparator func(v1, v2 K) int, data map[K]V, safe ...bool) *TreeMap[K, V]

NewTreeMapFrom instantiates a red-black tree with the custom key comparators and `data` map. The parameter `safe` is used to specify whether using tree in concurrent-safety, which is false in default.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}
	otherTree := g.NewTreeMapFrom[string, string](comparators.ComparatorString, tree.Map())
	fmt.Println(otherTree)
	// May Output:
	// │           ┌── key5
	// │       ┌── key4
	// │   ┌── key3
	// │   │   └── key2
	// └── key1
	//     └── key0
}

func (*TreeMap[K, V]) AscendingKeySet

func (tree *TreeMap[K, V]) AscendingKeySet() SortedSet[K]

AscendingKeySet returns a ascending order view of the keys contained in this map.

func (*TreeMap[K, V]) CeilingEntry

func (tree *TreeMap[K, V]) CeilingEntry(key K) MapEntry[K, V]

CeilingEntry finds ceiling node of the input key, return the ceiling node or nil if no ceiling node is found. Second return parameter is true if ceiling was found, otherwise false.

CeilingEntry node is defined as the smallest node that its key is larger than or equal to the given `key`. A ceiling node may not be found, either because the tree is empty, or because all nodes in the tree are smaller than the given node.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		if i != 50 {
			tree.Put(i, i)
		}
	}

	node := tree.CeilingEntry(1)
	if node != nil {
		fmt.Println("CeilingEntry 1:", node.Key())
	}

	node = tree.CeilingEntry(50)
	if node != nil {
		fmt.Println("CeilingEntry 50:", node.Key())
	}

	node = tree.CeilingEntry(100)
	if node != nil {
		fmt.Println("CeilingEntry 100:", node.Key())
	}

	node = tree.CeilingEntry(-1)
	if node != nil {
		fmt.Println("CeilingEntry -1:", node.Key())
	}

}
Output:
CeilingEntry 1: 1
CeilingEntry 50: 51
CeilingEntry -1: 1

func (*TreeMap[K, V]) CeilingKey

func (tree *TreeMap[K, V]) CeilingKey(key K) (ceilingKey K, ok bool)

CeilingKey returns the least key greater than or equal to the given key, or empty of type K if there is no such key. The parameter `ok` indicates whether a non-empty `ceilingKey` is returned.

func (*TreeMap[K, V]) Clear

func (tree *TreeMap[K, V]) Clear()

Clear removes all nodes from the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[int, string](comparators.ComparatorInt)
	for i := 0; i < 6; i++ {
		tree.Put(1000+i, "val"+gconv.String(i))
	}
	fmt.Println(tree.Size())

	tree.Clear()
	fmt.Println(tree.Size())

}
Output:
6
0

func (*TreeMap[K, V]) Clone

func (tree *TreeMap[K, V]) Clone(safe ...bool) Map[K, V]

Clone returns a new tree with a copy of current tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	b := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		b.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	tree := b.Clone()

	fmt.Println(tree.Map())
	fmt.Println(tree.Size())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]
6

func (*TreeMap[K, V]) Comparator

func (tree *TreeMap[K, V]) Comparator() comparators.Comparator[K]

func (*TreeMap[K, V]) ContainsKey

func (tree *TreeMap[K, V]) ContainsKey(key K) bool

ContainsKey checks whether `key` exists in the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.ContainsKey("key1"))
	fmt.Println(tree.ContainsKey("key6"))

}
Output:
true
false

func (*TreeMap[K, V]) DescendingKeySet

func (tree *TreeMap[K, V]) DescendingKeySet() SortedSet[K]

DescendingKeySet returns a reversed order view of the keys contained in this map.

func (*TreeMap[K, V]) FirstEntry

func (tree *TreeMap[K, V]) FirstEntry() MapEntry[K, V]

func (*TreeMap[K, V]) FloorEntry

func (tree *TreeMap[K, V]) FloorEntry(key K) MapEntry[K, V]

FloorEntry returns the tree node associated with the greatest key less than or equal to the given key, or nil if there is no such key. Second return parameter is true if FloorEntry was found, otherwise false.

A FloorEntry node may not be found, either because the tree is empty, or because all nodes in the tree are larger than the given node.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		if i != 50 {
			tree.Put(i, i)
		}
	}

	node := tree.FloorEntry(95)
	if node != nil {
		fmt.Println("FloorEntry 95:", node.Key())
	}

	node = tree.FloorEntry(50)
	if node != nil {
		fmt.Println("FloorEntry 50:", node.Key())
	}

	node = tree.FloorEntry(100)
	if node != nil {
		fmt.Println("FloorEntry 100:", node.Key())
	}

	node = tree.FloorEntry(0)
	if node != nil {
		fmt.Println("FloorEntry 0:", node.Key())
	}

}
Output:
FloorEntry 95: 95
FloorEntry 50: 49
FloorEntry 100: 99

func (*TreeMap[K, V]) FloorKey

func (tree *TreeMap[K, V]) FloorKey(key K) (floorKey K, ok bool)

FloorKey returns the greatest key less than or equal to the given key, or empty of type K if there is no such key. The parameter `ok` indicates whether a non-empty `floorKey` is returned.

func (*TreeMap[K, V]) ForEach

func (tree *TreeMap[K, V]) ForEach(f func(key K, value V) bool)

ForEach is alias of ForEachAsc.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	for i := 0; i < 10; i++ {
		tree.Put(i, 10-i)
	}

	var totalKey, totalValue int
	tree.ForEach(func(key, value int) bool {
		totalKey += key
		totalValue += value

		return totalValue < 20
	})

	fmt.Println("totalKey:", totalKey)
	fmt.Println("totalValue:", totalValue)

}
Output:
totalKey: 3
totalValue: 27

func (*TreeMap[K, V]) ForEachAsc

func (tree *TreeMap[K, V]) ForEachAsc(f func(key K, value V) bool)

ForEachAsc iterates the tree readonly in ascending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	for i := 0; i < 10; i++ {
		tree.Put(i, 10-i)
	}

	tree.ForEachAsc(func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 0 , value: 10
key: 1 , value: 9
key: 2 , value: 8
key: 3 , value: 7
key: 4 , value: 6
key: 5 , value: 5
key: 6 , value: 4
key: 7 , value: 3
key: 8 , value: 2
key: 9 , value: 1

func (*TreeMap[K, V]) ForEachDesc

func (tree *TreeMap[K, V]) ForEachDesc(f func(key K, value V) bool)

ForEachDesc iterates the tree readonly in descending order with given callback function `f`. If `f` returns true, then it continues iterating; or false to stop.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	for i := 0; i < 10; i++ {
		tree.Put(i, 10-i)
	}

	tree.ForEachDesc(func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 9 , value: 1
key: 8 , value: 2
key: 7 , value: 3
key: 6 , value: 4
key: 5 , value: 5
key: 4 , value: 6
key: 3 , value: 7
key: 2 , value: 8
key: 1 , value: 9
key: 0 , value: 10

func (*TreeMap[K, V]) Get

func (tree *TreeMap[K, V]) Get(key K) (value V)

Get returns the value by given `key`, or empty value of type K if the key is not found in the map.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Get("key1"))
	fmt.Println(tree.Get("key10"))

}
Output:
val1

func (*TreeMap[K, V]) GetOrPut

func (tree *TreeMap[K, V]) GetOrPut(key K, value V) V

GetOrPut returns the value by key, or sets value with given `value` if it does not exist and then returns this value.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.GetOrPut("key1", "newVal1"))
	fmt.Println(tree.GetOrPut("key6", "val6"))

}
Output:
val1
val6

func (*TreeMap[K, V]) GetOrPutFunc

func (tree *TreeMap[K, V]) GetOrPutFunc(key K, f func() V) V

GetOrPutFunc returns the value by key, or sets value with returned value of callback function `f` if it does not exist and then returns this value.

GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` with mutex.Lock of the hash map.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.GetOrPutFunc("key1", func() string {
		return "newVal1"
	}))
	fmt.Println(tree.GetOrPutFunc("key6", func() string {
		return "val6"
	}))

}
Output:
val1
val6

func (*TreeMap[K, V]) HeadMap

func (tree *TreeMap[K, V]) HeadMap(toKey K, inclusive bool) SortedMap[K, V]

HeadMap returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.

func (*TreeMap[K, V]) HigherEntry

func (tree *TreeMap[K, V]) HigherEntry(key K) MapEntry[K, V]

HigherEntry returns the tree node associated with the least key strictly greater than the given key, or nil if there is no such key. Second return parameter is true if HigherEntry was found, otherwise false.

A HigherEntry node may not be found, either because the tree is empty, or because all nodes in the tree are smaller than or equal to the given node.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		if i != 50 {
			tree.Put(i, i)
		}
	}

	node := tree.HigherEntry(1)
	if node != nil {
		fmt.Println("HigherEntry 1:", node.Key())
	}

	node = tree.HigherEntry(95)
	if node != nil {
		fmt.Println("HigherEntry 95:", node.Key())
	}

	node = tree.HigherEntry(50)
	if node != nil {
		fmt.Println("HigherEntry 50:", node.Key())
	}

	node = tree.HigherEntry(100)
	if node != nil {
		fmt.Println("HigherEntry 100:", node.Key())
	}

	node = tree.HigherEntry(-1)
	if node != nil {
		fmt.Println("HigherEntry -1:", node.Key())
	}

}
Output:
HigherEntry 1: 2
HigherEntry 95: 96
HigherEntry 50: 51
HigherEntry -1: 1

func (*TreeMap[K, V]) HigherKey

func (tree *TreeMap[K, V]) HigherKey(key K) (higherKey K, ok bool)

HigherKey returns the least key strictly greater than the given key, or empty of type K if there is no such key. The parameter `ok` indicates whether a non-empty `higherKey` is returned.

func (*TreeMap[K, V]) IsEmpty

func (tree *TreeMap[K, V]) IsEmpty() bool

IsEmpty returns true if tree does not contain any nodes.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)

	fmt.Println(tree.IsEmpty())

	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.IsEmpty())

}
Output:
true
false

func (*TreeMap[K, V]) IteratorAscFrom

func (tree *TreeMap[K, V]) IteratorAscFrom(key K, inclusive bool, f func(key K, value V) bool)

IteratorAscFrom iterates the tree readonly in ascending order with given callback function `f`. The parameter `key` specifies the start entry for iterating. The `match` specifies whether starting iterating if the `key` is fully matched, or else using index searching iterating. If `f` returns true, then it continues iterating; or false to stop.

Example (Inclusive)
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		if i == 3 {
			continue
		}
		m[i] = i * 10
	}
	tree := g.NewTreeMapFrom(comparators.ComparatorInt, m)

	tree.IteratorAscFrom(1, true, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

	tree.IteratorAscFrom(3, true, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 1 , value: 10
key: 2 , value: 20
key: 4 , value: 40
key: 5 , value: 50
key: 4 , value: 40
key: 5 , value: 50
Example (NonInclusive)
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		if i == 3 {
			continue
		}
		m[i] = i * 10
	}
	tree := g.NewTreeMapFrom(comparators.ComparatorInt, m)

	tree.IteratorAscFrom(1, false, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

	tree.IteratorAscFrom(3, false, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})
}
Output:
key: 2 , value: 20
key: 4 , value: 40
key: 5 , value: 50
key: 4 , value: 40
key: 5 , value: 50

func (*TreeMap[K, V]) IteratorDescFrom

func (tree *TreeMap[K, V]) IteratorDescFrom(key K, inclusive bool, f func(key K, value V) bool)

IteratorDescFrom iterates the tree readonly in descending order with given callback function `f`. The parameter `key` specifies the start entry for iterating. The `match` specifies whether starting iterating if the `key` is fully matched, or else using index searching iterating. If `f` returns true, then it continues iterating; or false to stop.

Example (Inclusive)
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		m[i] = i * 10
	}
	tree := g.NewTreeMapFrom(comparators.ComparatorInt, m)

	tree.IteratorDescFrom(5, true, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 5 , value: 50
key: 4 , value: 40
key: 3 , value: 30
key: 2 , value: 20
key: 1 , value: 10
Example (NonInclusive)
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		m[i] = i * 10
	}
	tree := g.NewTreeMapFrom(comparators.ComparatorInt, m)

	tree.IteratorDescFrom(5, false, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 4 , value: 40
key: 3 , value: 30
key: 2 , value: 20
key: 1 , value: 10

func (*TreeMap[K, V]) IteratorFrom

func (tree *TreeMap[K, V]) IteratorFrom(key K, inclusive bool, f func(key K, value V) bool)

IteratorFrom is alias of IteratorAscFrom.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	m := make(map[int]int)
	for i := 1; i <= 5; i++ {
		m[i] = i * 10
	}
	tree := g.NewTreeMapFrom[int, int](comparators.ComparatorInt, m)

	tree.IteratorFrom(1, true, func(key, value int) bool {
		fmt.Println("key:", key, ", value:", value)
		return true
	})

}
Output:
key: 1 , value: 10
key: 2 , value: 20
key: 3 , value: 30
key: 4 , value: 40
key: 5 , value: 50

func (*TreeMap[K, V]) KeySet added in v0.9.10

func (tree *TreeMap[K, V]) KeySet() Set[K]

KeySet returns a set of the keys contained in the tree.

func (*TreeMap[K, V]) Keys

func (tree *TreeMap[K, V]) Keys() []K

Keys returns all keys in asc order.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 6; i > 0; i-- {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Keys())

}
Output:
[key1 key2 key3 key4 key5 key6]

func (*TreeMap[K, V]) LastEntry

func (tree *TreeMap[K, V]) LastEntry() MapEntry[K, V]

func (*TreeMap[K, V]) Left

func (tree *TreeMap[K, V]) Left() *RedBlackTreeNode[K, V]

Left returns the left-most (min) node or nil if tree is empty.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		tree.Put(i, i)
	}
	fmt.Println(tree.Left().Key(), tree.Left().Value())

	emptyTree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	fmt.Println(emptyTree.Left())

}
Output:
1 1
<nil>

func (*TreeMap[K, V]) LowerEntry

func (tree *TreeMap[K, V]) LowerEntry(key K) MapEntry[K, V]

LowerEntry returns the tree node associated with the greatest key strictly less than the given key, or nil if there is no such key.

A LowerEntry node may not be found, either because the tree is empty, or because all nodes in the tree are larger than or equal to the given node.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		if i != 50 {
			tree.Put(i, i)
		}
	}

	node := tree.LowerEntry(95)
	if node != nil {
		fmt.Println("LowerEntry 95:", node.Key())
	}

	node = tree.LowerEntry(50)
	if node != nil {
		fmt.Println("LowerEntry 50:", node.Key())
	}

	node = tree.LowerEntry(100)
	if node != nil {
		fmt.Println("LowerEntry 100:", node.Key())
	}

	node = tree.LowerEntry(0)
	if node != nil {
		fmt.Println("LowerEntry 0:", node.Key())
	}

}
Output:
LowerEntry 95: 94
LowerEntry 50: 49
LowerEntry 100: 99

func (*TreeMap[K, V]) LowerKey

func (tree *TreeMap[K, V]) LowerKey(key K) (lowerKey K, ok bool)

LowerKey returns the greatest key strictly less than the given key, or empty of type K if there is no such key. The parameter `ok` indicates whether a non-empty `lowerKey` is returned.

func (*TreeMap[K, V]) Map

func (tree *TreeMap[K, V]) Map() map[K]V

Map returns all key-value items as map.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Map())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]

func (*TreeMap[K, V]) MapStrAny

func (tree *TreeMap[K, V]) MapStrAny() map[string]V

MapStrAny returns all key-value items as map[string]V.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[int, string](comparators.ComparatorInt)
	for i := 0; i < 6; i++ {
		tree.Put(1000+i, "val"+gconv.String(i))
	}

	fmt.Println(tree.MapStrAny())

}
Output:
map[1000:val0 1001:val1 1002:val2 1003:val3 1004:val4 1005:val5]

func (TreeMap[K, V]) MarshalJSON

func (tree TreeMap[K, V]) MarshalJSON() (jsonBytes []byte, err error)

MarshalJSON implements the interface MarshalJSON for json.Marshal.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/internal/json"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	bytes, err := json.Marshal(tree)
	if err == nil {
		fmt.Println(gconv.String(bytes))
	}

}
Output:
{"key0":"val0","key1":"val1","key2":"val2","key3":"val3","key4":"val4","key5":"val5"}

func (*TreeMap[K, V]) PollFirstEntry

func (tree *TreeMap[K, V]) PollFirstEntry() MapEntry[K, V]

func (*TreeMap[K, V]) PollLastEntry

func (tree *TreeMap[K, V]) PollLastEntry() MapEntry[K, V]

func (*TreeMap[K, V]) Print

func (tree *TreeMap[K, V]) Print()

Print prints the tree to stdout.

Example
package main

import (
	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	tree.Print()

}
Output:
│           ┌── key5
│       ┌── key4
│   ┌── key3
│   │   └── key2
└── key1
    └── key0

func (*TreeMap[K, V]) Put

func (tree *TreeMap[K, V]) Put(key K, value V)

Put inserts key-value item into the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Map())
	fmt.Println(tree.Size())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]
6

func (*TreeMap[K, V]) PutIfAbsent

func (tree *TreeMap[K, V]) PutIfAbsent(key K, value V) bool

PutIfAbsent sets `value` to the map if the `key` does not exist, and then returns true. It returns false if `key` exists, and `value` would be ignored.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.PutIfAbsent("key1", "newVal1"))
	fmt.Println(tree.PutIfAbsent("key6", "val6"))

}
Output:
false
true

func (*TreeMap[K, V]) PutIfAbsentFunc

func (tree *TreeMap[K, V]) PutIfAbsentFunc(key K, f func() V) bool

PutIfAbsentFunc sets value with return value of callback function `f`, and then returns true. It returns false if `key` exists, and `value` would be ignored.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.PutIfAbsentFunc("key1", func() string {
		return "newVal1"
	}))
	fmt.Println(tree.PutIfAbsentFunc("key6", func() string {
		return "val6"
	}))

}
Output:
false
true

func (*TreeMap[K, V]) Puts

func (tree *TreeMap[K, V]) Puts(data map[K]V)

Puts batch sets key-values to the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)

	tree.Puts(map[string]string{
		"key1": "val1",
		"key2": "val2",
	})

	fmt.Println(tree.Map())
	fmt.Println(tree.Size())

}
Output:
map[key1:val1 key2:val2]
2

func (*TreeMap[K, V]) Remove

func (tree *TreeMap[K, V]) Remove(key K) (value V, removed bool)

Remove removes the node from the tree by `key`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Remove("key1"))
	fmt.Println(tree.Remove("key6"))
	fmt.Println(tree.Map())

}
Output:
val1 true
 false
map[key0:val0 key2:val2 key3:val3 key4:val4 key5:val5]

func (*TreeMap[K, V]) Removes

func (tree *TreeMap[K, V]) Removes(keys []K)

Removes batch deletes values of the tree by `keys`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	removeKeys := make([]string, 2)
	removeKeys = append(removeKeys, "key1")
	removeKeys = append(removeKeys, "key6")

	tree.Removes(removeKeys)

	fmt.Println(tree.Map())

}
Output:
map[key0:val0 key2:val2 key3:val3 key4:val4 key5:val5]

func (*TreeMap[K, V]) Replace

func (tree *TreeMap[K, V]) Replace(data map[K]V)

Replace the data of the tree with given `data`.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Map())

	data := map[string]string{
		"newKey0": "newVal0",
		"newKey1": "newVal1",
		"newKey2": "newVal2",
	}

	tree.Replace(data)

	fmt.Println(tree.Map())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]
map[newKey0:newVal0 newKey1:newVal1 newKey2:newVal2]

func (*TreeMap[K, V]) Reverse

func (tree *TreeMap[K, V]) Reverse() SortedMap[K, V]

Reverse returns a reverse order view of the mappings contained in this map.

func (*TreeMap[K, V]) Right

func (tree *TreeMap[K, V]) Right() *RedBlackTreeNode[K, V]

Right returns the right-most (max) node or nil if tree is empty.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
)

func main() {
	tree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	for i := 1; i < 100; i++ {
		tree.Put(i, i)
	}
	fmt.Println(tree.Right().Key(), tree.Right().Value())

	emptyTree := g.NewTreeMap[int, int](comparators.ComparatorInt)
	fmt.Println(emptyTree.Left())

}
Output:
99 99
<nil>

func (*TreeMap[K, V]) Search

func (tree *TreeMap[K, V]) Search(key K) (value V, found bool)

Search searches the tree with given `key`. Second return parameter `found` is true if key was found, otherwise false.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Search("key0"))
	fmt.Println(tree.Search("key6"))

}
Output:
val0 true
 false

func (*TreeMap[K, V]) SetComparator

func (tree *TreeMap[K, V]) SetComparator(comparator comparators.Comparator[K])

SetComparator sets/changes the comparators for sorting.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	var tree g.TreeMap[string, string]
	tree.SetComparator(comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Map())
	fmt.Println(tree.Size())

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]
6

func (*TreeMap[K, V]) Size

func (tree *TreeMap[K, V]) Size() int

Size returns number of nodes in the tree.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)

	fmt.Println(tree.Size())

	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Size())

}
Output:
0
6

func (*TreeMap[K, V]) String

func (tree *TreeMap[K, V]) String() string

String returns a string representation of container.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.String())

}
Output:
│           ┌── key5
│       ┌── key4
│   ┌── key3
│   │   └── key2
└── key1
    └── key0

func (*TreeMap[K, V]) SubMap

func (tree *TreeMap[K, V]) SubMap(fromKey K, fromInclusive bool, toKey K, toInclusive bool) SortedMap[K, V]

SubMap returns a view of the portion of this map whose keys range from fromKey to toKey.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	m := make(map[string]int)
	for i := 0; i < 10; i++ {
		m["key"+gconv.String(i)] = i * 10
	}
	tree := g.NewTreeMapFrom(comparators.ComparatorString, m)

	fmt.Println(tree.SubMap("key5", true, "key7", true).Values())
	fmt.Println(tree.SubMap("key5", false, "key7", true).Values())
	fmt.Println(tree.SubMap("key5", true, "key7", false).Values())
	fmt.Println(tree.SubMap("key5", false, "key7", false).Values())
	fmt.Println(tree.SubMap("key5.1", true, "key7", true).Values())
	fmt.Println(tree.SubMap("key5.1", false, "key7", true).Values())
	fmt.Println(tree.SubMap("key5.1", true, "key7", false).Values())
	fmt.Println(tree.SubMap("key5.1", false, "key7", false).Values())
	fmt.Println(tree.SubMap("key5.1", true, "key7.1", true).Values())
	fmt.Println(tree.SubMap("key5.1", false, "key7.1", true).Values())
	fmt.Println(tree.SubMap("key5.1", true, "key7.1", false).Values())
	fmt.Println(tree.SubMap("key5.1", false, "key7.1", false).Values())
	fmt.Println(tree.SubMap("key9.1", false, "key7.1", false).Values())
	fmt.Println(tree.SubMap("key9.1", false, "key9.1", false).Values())
	fmt.Println(tree.SubMap("aa", false, "key0.1", false).Values())
	fmt.Println(tree.SubMap("aa", false, "bb", false).Values())
	fmt.Println(tree.SubMap("bb", false, "aa", false).Values())
	fmt.Println(tree.SubMap("yy", false, "zz", false).Values())
	fmt.Println(tree.SubMap("zz", false, "yy", false).Values())
	fmt.Println(tree.SubMap("key9", true, "zz", false).Values())

}
Output:
[50 60 70]
[60 70]
[50 60]
[60]
[60 70]
[60 70]
[60]
[60]
[60 70]
[60 70]
[60 70]
[60 70]
[]
[]
[0]
[]
[]
[]
[]
[90]

func (*TreeMap[K, V]) TailMap

func (tree *TreeMap[K, V]) TailMap(fromKey K, inclusive bool) SortedMap[K, V]

TailMap returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.

func (*TreeMap[K, V]) UnmarshalJSON

func (tree *TreeMap[K, V]) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/internal/json"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 0; i < 6; i++ {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}
	bytes, err := json.Marshal(tree)

	otherTree := g.NewTreeMap[string, string](comparators.ComparatorString)
	err = json.Unmarshal(bytes, &otherTree)
	if err == nil {
		fmt.Println(otherTree.Map())
	}

}
Output:
map[key0:val0 key1:val1 key2:val2 key3:val3 key4:val4 key5:val5]

func (*TreeMap[K, V]) UnmarshalValue

func (tree *TreeMap[K, V]) UnmarshalValue(value interface{}) (err error)

UnmarshalValue is an interface implement which sets any type of value for map.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)

	type User struct {
		Uid   string
		Name  string
		Pass1 string
		Pass2 string
	}

	var (
		user = User{
			Uid:   "1",
			Name:  "john",
			Pass1: "123",
			Pass2: "456",
		}
	)
	if err := gconv.Scan(user, tree); err == nil {
		fmt.Printf("%#v", tree.Map())
	}

}
Output:
map[string]string{"Name":"john", "Pass1":"123", "Pass2":"456", "Uid":"1"}

func (*TreeMap[K, V]) Values

func (tree *TreeMap[K, V]) Values() []V

Values returns all values in asc order based on the key.

Example
package main

import (
	"fmt"

	"github.com/wesleywu/gcontainer/g"
	"github.com/wesleywu/gcontainer/utils/comparators"
	"github.com/wesleywu/gcontainer/utils/gconv"
)

func main() {
	tree := g.NewTreeMap[string, string](comparators.ComparatorString)
	for i := 6; i > 0; i-- {
		tree.Put("key"+gconv.String(i), "val"+gconv.String(i))
	}

	fmt.Println(tree.Values())

}
Output:
[val1 val2 val3 val4 val5 val6]

type TreeSet

type TreeSet[T comparable] struct {
	// contains filtered or unexported fields
}

TreeSet is a golang sorted set with rich features. It is using increasing order in default, which can be changed by setting it a custom comparators. It contains a concurrent-safe/unsafe switch, which should be set when its initialization and cannot be changed then.

func NewTreeSet

func NewTreeSet[T comparable](comparator comparators.Comparator[T], safe ...bool) *TreeSet[T]

NewTreeSet creates and returns an empty sorted set. The parameter `safe` is used to specify whether using array in concurrent-safety, which is false in default. The parameter `comparators` used to compare values to sort in array, if it returns value < 0, means `a` < `b`; the `a` will be inserted before `b`; if it returns value = 0, means `a` = `b`; the `a` will be replaced by `b`; if it returns value > 0, means `a` > `b`; the `a` will be inserted after `b`;

func NewTreeSetDefault

func NewTreeSetDefault[T comparable](safe ...bool) *TreeSet[T]

NewTreeSetDefault creates and returns an empty sorted set using default comparators. The parameter `safe` is used to specify whether using array in concurrent-safety, which is false in default. if it returns value < 0, means `a` < `b`; the `a` will be inserted before `b`; if it returns value = 0, means `a` = `b`; the `a` will be replaced by `b`; if it returns value > 0, means `a` > `b`; the `a` will be inserted after `b`;

func NewTreeSetFrom

func NewTreeSetFrom[T comparable](elements []T, comparator comparators.Comparator[T], safe ...bool) *TreeSet[T]

NewTreeSetFrom creates and returns an sorted array with given slice `array`. The parameter `safe` is used to specify whether using array in concurrent-safety, which is false in default.

func (*TreeSet[T]) Add

func (t *TreeSet[T]) Add(elements ...T) bool

func (*TreeSet[T]) AddAll

func (t *TreeSet[T]) AddAll(elements Collection[T]) bool

func (*TreeSet[T]) Ceiling

func (t *TreeSet[T]) Ceiling(element T) (ceiling T, found bool)

func (*TreeSet[T]) Clear

func (t *TreeSet[T]) Clear()

func (*TreeSet[T]) Clone

func (t *TreeSet[T]) Clone() Collection[T]

func (*TreeSet[T]) Comparator

func (t *TreeSet[T]) Comparator() comparators.Comparator[T]

func (*TreeSet[T]) Complement added in v0.9.11

func (t *TreeSet[T]) Complement(full Set[T]) Set[T]

Complement returns a new set which is the complement from `t` to `full`. Which means, all the items in `newSet` are in `full` and not in `t`.

func (*TreeSet[T]) Contains

func (t *TreeSet[T]) Contains(element T) bool

func (*TreeSet[T]) ContainsAll

func (t *TreeSet[T]) ContainsAll(elements Collection[T]) bool

func (*TreeSet[T]) DeepCopy

func (t *TreeSet[T]) DeepCopy() Collection[T]

func (*TreeSet[T]) Diff added in v0.9.11

func (t *TreeSet[T]) Diff(others ...Set[T]) Set[T]

Diff returns a new set which is the difference set from `t` to `others`. Which means, all the items in `newSet` are in `t` but not in any of the `others`.

func (*TreeSet[T]) Equals

func (t *TreeSet[T]) Equals(another Collection[T]) bool

Equals checks whether the two sets equal.

func (*TreeSet[T]) First

func (t *TreeSet[T]) First() (element T, found bool)

func (*TreeSet[T]) Floor

func (t *TreeSet[T]) Floor(element T) (floor T, found bool)

func (*TreeSet[T]) ForEach

func (t *TreeSet[T]) ForEach(f func(T) bool)

func (*TreeSet[T]) ForEachDescending

func (t *TreeSet[T]) ForEachDescending(f func(T) bool)

func (*TreeSet[T]) HeadSet

func (t *TreeSet[T]) HeadSet(toElement T, inclusive bool) SortedSet[T]

func (*TreeSet[T]) Higher

func (t *TreeSet[T]) Higher(element T) (higher T, found bool)

func (*TreeSet[T]) Intersect added in v0.9.11

func (t *TreeSet[T]) Intersect(others ...Set[T]) Set[T]

Intersect returns a new set which is the intersection from `t` to `others`. Which means, all the items in `newSet` are in `t` and also in all the `others`.

func (*TreeSet[T]) IsDisjointWith added in v0.9.11

func (t *TreeSet[T]) IsDisjointWith(other Set[T]) bool

IsDisjointWith returns true if the current set has no elements in common with the given set.

func (*TreeSet[T]) IsEmpty

func (t *TreeSet[T]) IsEmpty() bool

func (*TreeSet[T]) IsSubsetOf added in v0.9.11

func (t *TreeSet[T]) IsSubsetOf(other Set[T]) bool

IsSubsetOf returns true if the current set is a subset of the given set.

func (*TreeSet[T]) IsSupersetOf added in v0.9.11

func (t *TreeSet[T]) IsSupersetOf(other Set[T]) bool

IsSupersetOf returns true if the current set is a superset of the given set.

func (*TreeSet[T]) Join

func (t *TreeSet[T]) Join(glue string) string

func (*TreeSet[T]) Last

func (t *TreeSet[T]) Last() (element T, found bool)

func (*TreeSet[T]) Lower

func (t *TreeSet[T]) Lower(element T) (lower T, found bool)

func (TreeSet[T]) MarshalJSON

func (t TreeSet[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements the interface MarshalJSON for json.Marshal.

func (*TreeSet[T]) Merge added in v0.9.11

func (t *TreeSet[T]) Merge(others ...Set[T]) Set[T]

Merge merges the given sets into the current set (in-place). This method modifies the current set by adding all elements from the given sets. Returns the current set after modification.

func (*TreeSet[T]) Permutation added in v0.9.12

func (t *TreeSet[T]) Permutation() [][]T

Permutation returns all possible permutations of the set elements. A permutation is a rearrangement of the elements. For a set with n elements, there are n! (n factorial) permutations. Returns a slice of slices, where each inner slice represents one permutation.

Example
// Create a new TreeSet with some elements
set := NewTreeSetFrom([]int{1, 2, 3}, comparators.ComparatorInt)

// Get all permutations
permutations := set.Permutation()

fmt.Printf("Set: %v\n", set.Slice())
fmt.Printf("Number of permutations: %d\n", len(permutations))
fmt.Println("All permutations:")

// Sort permutations for consistent output
sort.Slice(permutations, func(i, j int) bool {
	for k := 0; k < len(permutations[i]); k++ {
		if k >= len(permutations[j]) {
			return false
		}
		if permutations[i][k] != permutations[j][k] {
			return permutations[i][k] < permutations[j][k]
		}
	}
	return len(permutations[i]) < len(permutations[j])
})

for i, perm := range permutations {
	fmt.Printf("  %d: %v\n", i+1, perm)
}
Output:
Set: [1 2 3]
Number of permutations: 6
All permutations:
  1: [1 2 3]
  2: [1 3 2]
  3: [2 1 3]
  4: [2 3 1]
  5: [3 1 2]
  6: [3 2 1]

func (*TreeSet[T]) PollFirst

func (t *TreeSet[T]) PollFirst() (first T, found bool)

func (*TreeSet[T]) PollHeadSet added in v0.9.3

func (t *TreeSet[T]) PollHeadSet(toElement T, inclusive bool) SortedSet[T]

func (*TreeSet[T]) PollLast

func (t *TreeSet[T]) PollLast() (last T, found bool)

func (*TreeSet[T]) PollTailSet added in v0.9.3

func (t *TreeSet[T]) PollTailSet(fromElement T, inclusive bool) SortedSet[T]

func (*TreeSet[T]) Remove

func (t *TreeSet[T]) Remove(elements ...T) bool

func (*TreeSet[T]) RemoveAll

func (t *TreeSet[T]) RemoveAll(elements Collection[T]) bool

func (*TreeSet[T]) Size

func (t *TreeSet[T]) Size() int

func (*TreeSet[T]) Slice

func (t *TreeSet[T]) Slice() []T

func (*TreeSet[T]) String

func (t *TreeSet[T]) String() string

func (*TreeSet[T]) SubSet

func (t *TreeSet[T]) SubSet(fromElement T, fromInclusive bool, toElement T, toInclusive bool) SortedSet[T]

func (*TreeSet[T]) TailSet

func (t *TreeSet[T]) TailSet(fromElement T, inclusive bool) SortedSet[T]

func (*TreeSet[T]) Union added in v0.9.11

func (t *TreeSet[T]) Union(others ...Set[T]) Set[T]

Union returns a new set which is the union of `t` and `others`. Which means, all the items in `newSet` are in `t` or in `others`.

func (*TreeSet[T]) UnmarshalJSON

func (t *TreeSet[T]) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.

func (*TreeSet[T]) UnmarshalValue

func (t *TreeSet[T]) UnmarshalValue(value interface{}) (err error)

UnmarshalValue is an interface implement which sets any type of value for set.

func (*TreeSet[T]) Values added in v0.9.12

func (t *TreeSet[T]) Values() []T

Values returns all elements of the set as a slice, maintaining the order of elements in the set. This method is functionally identical to Slice() and is provided for consistency with Map interfaces.

Jump to

Keyboard shortcuts

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