github.com/alexandrestein/gods@v1.0.1/README.md (about)

     1  [![GoDoc](https://godoc.org/github.com/alexandrestein/gods?status.svg)](https://godoc.org/github.com/alexandrestein/gods) [![Build Status](https://travis-ci.org/emirpasic/gods.svg)](https://travis-ci.org/emirpasic/gods) [![Go Report Card](https://goreportcard.com/badge/github.com/alexandrestein/gods)](https://goreportcard.com/report/github.com/alexandrestein/gods) [![PyPI](https://img.shields.io/pypi/l/Django.svg?maxAge=2592000)](https://github.com/alexandrestein/gods/blob/master/LICENSE)
     2  
     3  # GoDS (Go Data Structures)
     4  
     5  Implementation of various data structures and algorithms in Go.
     6  
     7  ## Data Structures
     8  
     9  - [Containers](#containers)
    10    - [Lists](#lists)
    11      - [ArrayList](#arraylist)
    12      - [SinglyLinkedList](#singlylinkedlist)
    13      - [DoublyLinkedList](#doublylinkedlist)
    14    - [Sets](#sets)
    15      - [HashSet](#hashset)
    16      - [TreeSet](#treeset)
    17    - [Stacks](#stacks)
    18      - [LinkedListStack](#linkedliststack)
    19      - [ArrayStack](#arraystack)
    20    - [Maps](#maps)
    21      - [HashMap](#hashmap)
    22      - [TreeMap](#treemap)
    23      - [HashBidiMap](#hashbidimap)
    24      - [TreeBidiMap](#treebidimap)
    25    - [Trees](#trees)
    26      - [RedBlackTree](#redblacktree)
    27      - [AVLTree](#avltree)
    28      - [BTree](#btree)
    29      - [BinaryHeap](#binaryheap)
    30  - [Functions](#functions)
    31      - [Comparator](#comparator)
    32      - [Iterator](#iterator)
    33        - [IteratorWithIndex](#iteratorwithindex)
    34        - [IteratorWithKey](#iteratorwithkey)
    35        - [ReverseIteratorWithIndex](#reverseiteratorwithindex)
    36        - [ReverseIteratorWithKey](#reverseiteratorwithkey)
    37      - [Enumerable](#enumerable)
    38        - [EnumerableWithIndex](#enumerablewithindex)
    39        - [EnumerableWithKey](#enumerablewithkey)
    40      - [Serialization](#serialization)
    41        - [JSONSerializer](#jsonserializer)
    42        - [JSONDeserializer](#jsondeserializer)
    43      - [Sort](#sort)
    44      - [Container](#container)
    45  - [Appendix](#appendix)
    46  
    47  
    48  ## Containers
    49  
    50  All data structures implement the container interface with the following methods:
    51  
    52  ```go
    53  type Container interface {
    54  	Empty() bool
    55  	Size() int
    56  	Clear()
    57  	Values() []interface{}
    58  }
    59  ```
    60  
    61  Containers are either ordered or unordered. All ordered containers provide [stateful iterators](#iterator) and some of them allow [enumerable functions](#enumerable).
    62  
    63  | Container | Ordered | [Iterator](#iterator) | [Enumerable](#enumerable) | Referenced by |
    64  | :--- | :---: | :---: | :---: | :---: |
    65  | [ArrayList](#arraylist) | yes | yes* | yes | index |
    66  | [SinglyLinkedList](#singlylinkedlist) | yes | yes | yes | index |
    67  | [DoublyLinkedList](#doublylinkedlist) | yes | yes* | yes | index |
    68  | [HashSet](#hashset) | no | no | no | index |
    69  | [TreeSet](#treeset) | yes | yes* | yes | index |
    70  | [LinkedListStack](#linkedliststack) | yes | yes | no | index |
    71  | [ArrayStack](#arraystack) | yes | yes* | no | index |
    72  | [HashMap](#hashmap) | no | no | no | key |
    73  | [TreeMap](#treemap) | yes | yes* | yes | key |
    74  | [HashBidiMap](#hashbidimap) | no | no | no | key* |
    75  | [TreeBidiMap](#treebidimap) | yes | yes* | yes | key* |
    76  | [RedBlackTree](#redblacktree) | yes | yes* | no | key |
    77  | [AVLTree](#avltree) | yes | yes* | no | key |
    78  | [BTree](#btree) | yes | yes* | no | key |
    79  | [BinaryHeap](#binaryheap) | yes | yes* | no | index |
    80  |  |  | <sub><sup>*reversible</sup></sub> |  | <sub><sup>*bidirectional</sup></sub> |
    81  
    82  ### Lists
    83  
    84  A list is a data structure that stores values and may have repeated values.
    85  
    86  Implements [Container](#containers) interface.
    87  
    88  ```go
    89  type List interface {
    90  	Get(index int) (interface{}, bool)
    91  	Remove(index int)
    92  	Add(values ...interface{})
    93  	Contains(values ...interface{}) bool
    94  	Sort(comparator utils.Comparator)
    95  	Swap(index1, index2 int)
    96  	Insert(index int, values ...interface{})
    97  
    98  	containers.Container
    99  	// Empty() bool
   100  	// Size() int
   101  	// Clear()
   102  	// Values() []interface{}
   103  }
   104  ```
   105  
   106  #### ArrayList
   107  
   108  A [list](#lists) backed by a dynamic array that grows and shrinks implicitly.
   109  
   110  Implements [List](#lists), [IteratorWithIndex](#iteratorwithindex), [EnumerableWithIndex](#enumerablewithindex), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   111  
   112  ```go
   113  package main
   114  
   115  import (
   116  	"github.com/alexandrestein/gods/lists/arraylist"
   117  	"github.com/alexandrestein/gods/utils"
   118  )
   119  
   120  func main() {
   121  	list := arraylist.New()
   122  	list.Add("a")                         // ["a"]
   123  	list.Add("c", "b")                    // ["a","c","b"]
   124  	list.Sort(utils.StringComparator)     // ["a","b","c"]
   125  	_, _ = list.Get(0)                    // "a",true
   126  	_, _ = list.Get(100)                  // nil,false
   127  	_ = list.Contains("a", "b", "c")      // true
   128  	_ = list.Contains("a", "b", "c", "d") // false
   129  	list.Swap(0, 1)                       // ["b","a",c"]
   130  	list.Remove(2)                        // ["b","a"]
   131  	list.Remove(1)                        // ["b"]
   132  	list.Remove(0)                        // []
   133  	list.Remove(0)                        // [] (ignored)
   134  	_ = list.Empty()                      // true
   135  	_ = list.Size()                       // 0
   136  	list.Add("a")                         // ["a"]
   137  	list.Clear()                          // []
   138  	list.Insert(0, "b")                   // ["b"]
   139  	list.Insert(0, "a")                   // ["a","b"]
   140  }
   141  ```
   142  
   143  #### SinglyLinkedList
   144  
   145  A [list](#lists) where each element points to the next element in the list.
   146  
   147  Implements [List](#lists), [IteratorWithIndex](#iteratorwithindex), [EnumerableWithIndex](#enumerablewithindex), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   148  
   149  ```go
   150  package main
   151  
   152  import (
   153  	sll "github.com/alexandrestein/gods/lists/singlylinkedlist"
   154  	"github.com/alexandrestein/gods/utils"
   155  )
   156  
   157  func main() {
   158  	list := sll.New()
   159  	list.Add("a")                         // ["a"]
   160  	list.Add("c", "b")                    // ["a","c","b"]
   161  	list.Sort(utils.StringComparator)     // ["a","b","c"]
   162  	_, _ = list.Get(0)                    // "a",true
   163  	_, _ = list.Get(100)                  // nil,false
   164  	_ = list.Contains("a", "b", "c")      // true
   165  	_ = list.Contains("a", "b", "c", "d") // false
   166  	list.Swap(0, 1)                       // ["b","a",c"]
   167  	list.Remove(2)                        // ["b","a"]
   168  	list.Remove(1)                        // ["b"]
   169  	list.Remove(0)                        // []
   170  	list.Remove(0)                        // [] (ignored)
   171  	_ = list.Empty()                      // true
   172  	_ = list.Size()                       // 0
   173  	list.Add("a")                         // ["a"]
   174  	list.Clear()                          // []
   175  	list.Insert(0, "b")                   // ["b"]
   176  	list.Insert(0, "a")                   // ["a","b"]
   177  }
   178  ```
   179  
   180  #### DoublyLinkedList
   181  
   182  A [list](#lists) where each element points to the next and previous elements in the list.
   183  
   184  Implements [List](#lists), [IteratorWithIndex](#iteratorwithindex), [EnumerableWithIndex](#enumerablewithindex), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   185  
   186  ```go
   187  package main
   188  
   189  import (
   190  	dll "github.com/alexandrestein/gods/lists/doublylinkedlist"
   191  	"github.com/alexandrestein/gods/utils"
   192  )
   193  
   194  func main() {
   195  	list := dll.New()
   196  	list.Add("a")                         // ["a"]
   197  	list.Add("c", "b")                    // ["a","c","b"]
   198  	list.Sort(utils.StringComparator)     // ["a","b","c"]
   199  	_, _ = list.Get(0)                    // "a",true
   200  	_, _ = list.Get(100)                  // nil,false
   201  	_ = list.Contains("a", "b", "c")      // true
   202  	_ = list.Contains("a", "b", "c", "d") // false
   203  	list.Swap(0, 1)                       // ["b","a",c"]
   204  	list.Remove(2)                        // ["b","a"]
   205  	list.Remove(1)                        // ["b"]
   206  	list.Remove(0)                        // []
   207  	list.Remove(0)                        // [] (ignored)
   208  	_ = list.Empty()                      // true
   209  	_ = list.Size()                       // 0
   210  	list.Add("a")                         // ["a"]
   211  	list.Clear()                          // []
   212  	list.Insert(0, "b")                   // ["b"]
   213  	list.Insert(0, "a")                   // ["a","b"]
   214  }
   215  ```
   216  
   217  ### Sets
   218  
   219  A set is a data structure that can store elements and has no repeated values. It is a computer implementation of the mathematical concept of a finite set. Unlike most other collection types, rather than retrieving a specific element from a set, one typically tests an element for membership in a set. This structure is often used to ensure that no duplicates are present in a container.
   220  
   221  Implements [Container](#containers) interface.
   222  
   223  ```go
   224  type Set interface {
   225  	Add(elements ...interface{})
   226  	Remove(elements ...interface{})
   227  	Contains(elements ...interface{}) bool
   228  
   229  	containers.Container
   230  	// Empty() bool
   231  	// Size() int
   232  	// Clear()
   233  	// Values() []interface{}
   234  }
   235  ```
   236  
   237  #### HashSet
   238  
   239  A [set](#sets) backed by a hash table (actually a Go's map). It makes no guarantees as to the iteration order of the set.
   240  
   241  Implements [Set](#sets), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   242  
   243  ```go
   244  package main
   245  
   246  import "github.com/alexandrestein/gods/sets/hashset"
   247  
   248  func main() {
   249  	set := hashset.New()   // empty
   250  	set.Add(1)             // 1
   251  	set.Add(2, 2, 3, 4, 5) // 3, 1, 2, 4, 5 (random order, duplicates ignored)
   252  	set.Remove(4)          // 5, 3, 2, 1 (random order)
   253  	set.Remove(2, 3)       // 1, 5 (random order)
   254  	set.Contains(1)        // true
   255  	set.Contains(1, 5)     // true
   256  	set.Contains(1, 6)     // false
   257  	_ = set.Values()       // []int{5,1} (random order)
   258  	set.Clear()            // empty
   259  	set.Empty()            // true
   260  	set.Size()             // 0
   261  }
   262  ```
   263  
   264  #### TreeSet
   265  
   266  A [set](#sets) backed by a [red-black tree](#redblacktree) to keep the elements ordered with respect to the [comparator](#comparator).
   267  
   268  Implements [Set](#sets), [IteratorWithIndex](#iteratorwithindex), [EnumerableWithIndex](#enumerablewithindex), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   269  
   270  ```go
   271  package main
   272  
   273  import "github.com/alexandrestein/gods/sets/treeset"
   274  
   275  func main() {
   276  	set := treeset.NewWithIntComparator() // empty (keys are of type int)
   277  	set.Add(1)                            // 1
   278  	set.Add(2, 2, 3, 4, 5)                // 1, 2, 3, 4, 5 (in order, duplicates ignored)
   279  	set.Remove(4)                         // 1, 2, 3, 5 (in order)
   280  	set.Remove(2, 3)                      // 1, 5 (in order)
   281  	set.Contains(1)                       // true
   282  	set.Contains(1, 5)                    // true
   283  	set.Contains(1, 6)                    // false
   284  	_ = set.Values()                      // []int{1,5} (in order)
   285  	set.Clear()                           // empty
   286  	set.Empty()                           // true
   287  	set.Size()                            // 0
   288  }
   289  ```
   290  
   291  ### Stacks
   292  
   293  A stack that represents a last-in-first-out (LIFO) data structure. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack.
   294  
   295  Implements [Container](#containers) interface.
   296  
   297  ```go
   298  type Stack interface {
   299  	Push(value interface{})
   300  	Pop() (value interface{}, ok bool)
   301  	Peek() (value interface{}, ok bool)
   302  
   303  	containers.Container
   304  	// Empty() bool
   305  	// Size() int
   306  	// Clear()
   307  	// Values() []interface{}
   308  }
   309  ```
   310  
   311  #### LinkedListStack
   312  
   313  A [stack](#stacks) based on a [linked list](#singlylinkedlist).
   314  
   315  Implements [Stack](#stacks), [IteratorWithIndex](#iteratorwithindex), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   316  
   317  ```go
   318  package main
   319  
   320  import lls "github.com/alexandrestein/gods/stacks/linkedliststack"
   321  
   322  func main() {
   323  	stack := lls.New()  // empty
   324  	stack.Push(1)       // 1
   325  	stack.Push(2)       // 1, 2
   326  	stack.Values()      // 2, 1 (LIFO order)
   327  	_, _ = stack.Peek() // 2,true
   328  	_, _ = stack.Pop()  // 2, true
   329  	_, _ = stack.Pop()  // 1, true
   330  	_, _ = stack.Pop()  // nil, false (nothing to pop)
   331  	stack.Push(1)       // 1
   332  	stack.Clear()       // empty
   333  	stack.Empty()       // true
   334  	stack.Size()        // 0
   335  }
   336  ```
   337  
   338  #### ArrayStack
   339  
   340  A [stack](#stacks) based on a [array list](#arraylist).
   341  
   342  Implements [Stack](#stacks), [IteratorWithIndex](#iteratorwithindex), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   343  
   344  ```go
   345  package main
   346  
   347  import "github.com/alexandrestein/gods/stacks/arraystack"
   348  
   349  func main() {
   350  	stack := arraystack.New() // empty
   351  	stack.Push(1)             // 1
   352  	stack.Push(2)             // 1, 2
   353  	stack.Values()            // 2, 1 (LIFO order)
   354  	_, _ = stack.Peek()       // 2,true
   355  	_, _ = stack.Pop()        // 2, true
   356  	_, _ = stack.Pop()        // 1, true
   357  	_, _ = stack.Pop()        // nil, false (nothing to pop)
   358  	stack.Push(1)             // 1
   359  	stack.Clear()             // empty
   360  	stack.Empty()             // true
   361  	stack.Size()              // 0
   362  }
   363  ```
   364  
   365  ### Maps
   366  
   367  A Map is a data structure that maps keys to values. A map cannot contain duplicate keys and each key can map to at most one value.
   368  
   369  Implements [Container](#containers) interface.
   370  
   371  ```go
   372  type Map interface {
   373  	Put(key interface{}, value interface{})
   374  	Get(key interface{}) (value interface{}, found bool)
   375  	Remove(key interface{})
   376  	Keys() []interface{}
   377  
   378  	containers.Container
   379  	// Empty() bool
   380  	// Size() int
   381  	// Clear()
   382  	// Values() []interface{}
   383  }
   384  ```
   385  
   386  A BidiMap is an extension to the Map. A bidirectional map (BidiMap), also called a hash bag, is an associative data structure in which the key-value pairs form a one-to-one relation. This relation works in both directions by allow the value to also act as a key to key, e.g. a pair (a,b) thus provides a coupling between 'a' and 'b' so that 'b' can be found when 'a' is used as a key and 'a' can be found when 'b' is used as a key.
   387  
   388  ```go
   389  type BidiMap interface {
   390  	GetKey(value interface{}) (key interface{}, found bool)
   391  
   392  	Map
   393  }
   394  ```
   395  
   396  #### HashMap
   397  
   398  A [map](#maps) based on hash tables. Keys are unordered.
   399  
   400  Implements [Map](#maps), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   401  
   402  ```go
   403  package main
   404  
   405  import "github.com/alexandrestein/gods/maps/hashmap"
   406  
   407  func main() {
   408  	m := hashmap.New() // empty
   409  	m.Put(1, "x")      // 1->x
   410  	m.Put(2, "b")      // 2->b, 1->x (random order)
   411  	m.Put(1, "a")      // 2->b, 1->a (random order)
   412  	_, _ = m.Get(2)    // b, true
   413  	_, _ = m.Get(3)    // nil, false
   414  	_ = m.Values()     // []interface {}{"b", "a"} (random order)
   415  	_ = m.Keys()       // []interface {}{1, 2} (random order)
   416  	m.Remove(1)        // 2->b
   417  	m.Clear()          // empty
   418  	m.Empty()          // true
   419  	m.Size()           // 0
   420  }
   421  ```
   422  
   423  #### TreeMap
   424  
   425  A [map](#maps) based on [red-black tree](#redblacktree). Keys are ordered  ordered with respect to the [comparator](#comparator).
   426  
   427  Implements [Map](#maps), [IteratorWithKey](#iteratorwithkey), [EnumerableWithKey](#enumerablewithkey), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   428  
   429  ```go
   430  package main
   431  
   432  import "github.com/alexandrestein/gods/maps/treemap"
   433  
   434  func main() {
   435  	m := treemap.NewWithIntComparator() // empty (keys are of type int)
   436  	m.Put(1, "x")                       // 1->x
   437  	m.Put(2, "b")                       // 1->x, 2->b (in order)
   438  	m.Put(1, "a")                       // 1->a, 2->b (in order)
   439  	_, _ = m.Get(2)                     // b, true
   440  	_, _ = m.Get(3)                     // nil, false
   441  	_ = m.Values()                      // []interface {}{"a", "b"} (in order)
   442  	_ = m.Keys()                        // []interface {}{1, 2} (in order)
   443  	m.Remove(1)                         // 2->b
   444  	m.Clear()                           // empty
   445  	m.Empty()                           // true
   446  	m.Size()                            // 0
   447  
   448  	// Other:
   449  	m.Min() // Returns the minimum key and its value from map.
   450  	m.Max() // Returns the maximum key and its value from map.
   451  }
   452  ```
   453  
   454  #### HashBidiMap
   455  
   456  A [map](#maps) based on two hashmaps. Keys are unordered.
   457  
   458  Implements [BidiMap](#maps), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   459  
   460  ```go
   461  package main
   462  
   463  import "github.com/alexandrestein/gods/maps/hashbidimap"
   464  
   465  func main() {
   466  	m := hashbidimap.New() // empty
   467  	m.Put(1, "x")          // 1->x
   468  	m.Put(3, "b")          // 1->x, 3->b (random order)
   469  	m.Put(1, "a")          // 1->a, 3->b (random order)
   470  	m.Put(2, "b")          // 1->a, 2->b (random order)
   471  	_, _ = m.GetKey("a")   // 1, true
   472  	_, _ = m.Get(2)        // b, true
   473  	_, _ = m.Get(3)        // nil, false
   474  	_ = m.Values()         // []interface {}{"a", "b"} (random order)
   475  	_ = m.Keys()           // []interface {}{1, 2} (random order)
   476  	m.Remove(1)            // 2->b
   477  	m.Clear()              // empty
   478  	m.Empty()              // true
   479  	m.Size()               // 0
   480  }
   481  ```
   482  
   483  #### TreeBidiMap
   484  
   485  A [map](#maps) based on red-black tree. This map guarantees that the map will be in both ascending key and value order.  Other than key and value ordering, the goal with this structure is to avoid duplication of elements (unlike in [HashBidiMap](#hashbidimap)), which can be significant if contained elements are large.
   486  
   487  Implements [BidiMap](#maps), [IteratorWithKey](#iteratorwithkey), [EnumerableWithKey](#enumerablewithkey), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   488  
   489  ```go
   490  package main
   491  
   492  import (
   493  	"github.com/alexandrestein/gods/maps/treebidimap"
   494  	"github.com/alexandrestein/gods/utils"
   495  )
   496  
   497  func main() {
   498  	m := treebidimap.NewWith(utils.IntComparator, utils.StringComparator)
   499  	m.Put(1, "x")        // 1->x
   500  	m.Put(3, "b")        // 1->x, 3->b (ordered)
   501  	m.Put(1, "a")        // 1->a, 3->b (ordered)
   502  	m.Put(2, "b")        // 1->a, 2->b (ordered)
   503  	_, _ = m.GetKey("a") // 1, true
   504  	_, _ = m.Get(2)      // b, true
   505  	_, _ = m.Get(3)      // nil, false
   506  	_ = m.Values()       // []interface {}{"a", "b"} (ordered)
   507  	_ = m.Keys()         // []interface {}{1, 2} (ordered)
   508  	m.Remove(1)          // 2->b
   509  	m.Clear()            // empty
   510  	m.Empty()            // true
   511  	m.Size()             // 0
   512  }
   513  ```
   514  
   515  ### Trees
   516  
   517  A tree is a widely used data data structure that simulates a hierarchical tree structure, with a root value and subtrees of children, represented as a set of linked nodes; thus no cyclic links.
   518  
   519  Implements [Container](#containers) interface.
   520  
   521  ```go
   522  type Tree interface {
   523  	containers.Container
   524  	// Empty() bool
   525  	// Size() int
   526  	// Clear()
   527  	// Values() []interface{}
   528  }
   529  ```
   530  
   531  #### RedBlackTree
   532  
   533  A red–black [tree](#trees) is a binary search tree with an extra bit of data per node, its color, which can be either red or black. The extra bit of storage ensures an approximately balanced tree by constraining how nodes are colored from any path from the root to the leaf. Thus, it is a data structure which is a type of self-balancing binary search tree.
   534  
   535  The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching in O(log n) time, where n is the total number of elements in the tree. The insertion and deletion operations, along with the tree rearrangement and recoloring, are also performed in O(log n) time. <sub><sup>[Wikipedia](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree)</sup></sub>
   536  
   537  Implements [Tree](#trees), [ReverseIteratorWithKey](#reverseiteratorwithkey), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   538  
   539  <p align="center"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/6/66/Red-black_tree_example.svg/500px-Red-black_tree_example.svg.png" width="400px" height="200px" /></p>
   540  
   541  ```go
   542  package main
   543  
   544  import (
   545  	"fmt"
   546  	rbt "github.com/alexandrestein/gods/trees/redblacktree"
   547  )
   548  
   549  func main() {
   550  	tree := rbt.NewWithIntComparator() // empty (keys are of type int)
   551  
   552  	tree.Put(1, "x") // 1->x
   553  	tree.Put(2, "b") // 1->x, 2->b (in order)
   554  	tree.Put(1, "a") // 1->a, 2->b (in order, replacement)
   555  	tree.Put(3, "c") // 1->a, 2->b, 3->c (in order)
   556  	tree.Put(4, "d") // 1->a, 2->b, 3->c, 4->d (in order)
   557  	tree.Put(5, "e") // 1->a, 2->b, 3->c, 4->d, 5->e (in order)
   558  	tree.Put(6, "f") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f (in order)
   559  
   560  	fmt.Println(tree)
   561  	//
   562  	//  RedBlackTree
   563  	//  │           ┌── 6
   564  	//	│       ┌── 5
   565  	//	│   ┌── 4
   566  	//	│   │   └── 3
   567  	//	└── 2
   568  	//		└── 1
   569  
   570  	_ = tree.Values() // []interface {}{"a", "b", "c", "d", "e", "f"} (in order)
   571  	_ = tree.Keys()   // []interface {}{1, 2, 3, 4, 5, 6} (in order)
   572  
   573  	tree.Remove(2) // 1->a, 3->c, 4->d, 5->e, 6->f (in order)
   574  	fmt.Println(tree)
   575  	//
   576  	//  RedBlackTree
   577  	//  │       ┌── 6
   578  	//  │   ┌── 5
   579  	//  └── 4
   580  	//      │   ┌── 3
   581  	//      └── 1
   582  
   583  	tree.Clear() // empty
   584  	tree.Empty() // true
   585  	tree.Size()  // 0
   586  
   587  	// Other:
   588  	tree.Left() // gets the left-most (min) node
   589  	tree.Right() // get the right-most (max) node
   590  	tree.Floor(1) // get the floor node
   591  	tree.Ceiling(1) // get the ceiling node
   592  }
   593  ```
   594  
   595  Extending the red-black tree's functionality  has been demonstrated in the following [example](https://github.com/alexandrestein/gods/blob/master/examples/redblacktreeextended.go).
   596  
   597  #### AVLTree
   598  
   599  AVL [tree](#trees) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations.
   600  
   601  AVL trees are often compared with red–black trees because both support the same set of operations and take O(log n) time for the basic operations. For lookup-intensive applications, AVL trees are faster than red–black trees because they are more strictly balanced. <sub><sup>[Wikipedia](https://en.wikipedia.org/wiki/AVL_tree)</sup></sub>
   602  
   603  Implements [Tree](#trees), [ReverseIteratorWithKey](#reverseiteratorwithkey), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   604  
   605  <p align="center"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ad/AVL-tree-wBalance_K.svg/262px-AVL-tree-wBalance_K.svg.png" width="300px" height="180px" /><br/><sub>AVL tree with balance factors (green)</sub></p>
   606  
   607  ```go
   608  package main
   609  
   610  import (
   611  	"fmt"
   612  	avl "github.com/alexandrestein/gods/trees/avltree"
   613  )
   614  
   615  func main() {
   616  	tree := avl.NewWithIntComparator() // empty(keys are of type int)
   617  
   618  	tree.Put(1, "x") // 1->x
   619  	tree.Put(2, "b") // 1->x, 2->b (in order)
   620  	tree.Put(1, "a") // 1->a, 2->b (in order, replacement)
   621  	tree.Put(3, "c") // 1->a, 2->b, 3->c (in order)
   622  	tree.Put(4, "d") // 1->a, 2->b, 3->c, 4->d (in order)
   623  	tree.Put(5, "e") // 1->a, 2->b, 3->c, 4->d, 5->e (in order)
   624  	tree.Put(6, "f") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f (in order)
   625  
   626  	fmt.Println(tree)
   627  	//
   628  	//  AVLTree
   629  	//  │       ┌── 6
   630  	//  │   ┌── 5
   631  	//  └── 4
   632  	//      │   ┌── 3
   633  	//      └── 2
   634  	//          └── 1
   635  
   636  
   637  	_ = tree.Values() // []interface {}{"a", "b", "c", "d", "e", "f"} (in order)
   638  	_ = tree.Keys()   // []interface {}{1, 2, 3, 4, 5, 6} (in order)
   639  
   640  	tree.Remove(2) // 1->a, 3->c, 4->d, 5->e, 6->f (in order)
   641  	fmt.Println(tree)
   642  	//
   643  	//  AVLTree
   644  	//  │       ┌── 6
   645  	//  │   ┌── 5
   646  	//  └── 4
   647  	//      └── 3
   648  	//          └── 1
   649  
   650  	tree.Clear() // empty
   651  	tree.Empty() // true
   652  	tree.Size()  // 0
   653  }
   654  ```
   655  
   656  #### BTree
   657  
   658  B-tree is a self-balancing tree data structure that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time. The B-tree is a generalization of a binary search tree in that a node can have more than two children.
   659  
   660  According to Knuth's definition, a B-tree of order m is a tree which satisfies the following properties:
   661  
   662  - Every node has at most m children.
   663  - Every non-leaf node (except root) has at least ⌈m/2⌉ children.
   664  - The root has at least two children if it is not a leaf node.
   665  - A non-leaf node with k children contains k−1 keys.
   666  - All leaves appear in the same level
   667  
   668  Each internal node’s keys act as separation values which divide its subtrees. For example, if an internal node has 3 child nodes (or subtrees) then it must have 2 keys: a1 and a2. All values in the leftmost subtree will be less than a1, all values in the middle subtree will be between a1 and a2, and all values in the rightmost subtree will be greater than a2.<sub><sup>[Wikipedia](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree)</sub></sup>
   669  
   670  Implements [Tree](#trees), [ReverseIteratorWithKey](#reverseiteratorwithkey), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   671  
   672  <p align="center"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/B-tree.svg/831px-B-tree.svg.png" width="400px" height="111px" /></p>
   673  
   674  ```go
   675  package main
   676  
   677  import (
   678  	"fmt"
   679  	"github.com/alexandrestein/gods/trees/btree"
   680  )
   681  
   682  func main() {
   683  	tree := btree.NewWithIntComparator(3) // empty (keys are of type int)
   684  
   685  	tree.Put(1, "x") // 1->x
   686  	tree.Put(2, "b") // 1->x, 2->b (in order)
   687  	tree.Put(1, "a") // 1->a, 2->b (in order, replacement)
   688  	tree.Put(3, "c") // 1->a, 2->b, 3->c (in order)
   689  	tree.Put(4, "d") // 1->a, 2->b, 3->c, 4->d (in order)
   690  	tree.Put(5, "e") // 1->a, 2->b, 3->c, 4->d, 5->e (in order)
   691  	tree.Put(6, "f") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f (in order)
   692  	tree.Put(7, "g") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f, 7->g (in order)
   693  
   694  	fmt.Println(tree)
   695  	// BTree
   696  	//         1
   697  	//     2
   698  	//         3
   699  	// 4
   700  	//         5
   701  	//     6
   702  	//         7
   703  
   704  	_ = tree.Values() // []interface {}{"a", "b", "c", "d", "e", "f", "g"} (in order)
   705  	_ = tree.Keys()   // []interface {}{1, 2, 3, 4, 5, 6, 7} (in order)
   706  
   707  	tree.Remove(2) // 1->a, 3->c, 4->d, 5->e, 6->f (in order)
   708  	fmt.Println(tree)
   709  	// BTree
   710  	//     1
   711  	//     3
   712  	// 4
   713  	//     5
   714  	//     6
   715  
   716  	tree.Clear() // empty
   717  	tree.Empty() // true
   718  	tree.Size()  // 0
   719  
   720  	// Other:
   721  	tree.Height() // gets the height of the tree
   722  	tree.Left() // gets the left-most (min) node
   723  	tree.LeftKey() // get the left-most (min) node's key
   724  	tree.LeftValue() // get the left-most (min) node's value
   725  	tree.Right() // get the right-most (max) node
   726  	tree.RightKey() // get the right-most (max) node's key
   727  	tree.RightValue() // get the right-most (max) node's value
   728  }
   729  ```
   730  
   731  #### BinaryHeap
   732  
   733  A binary heap is a [tree](#trees) created using a binary tree. It can be seen as a binary tree with two additional constraints:
   734  
   735  - Shape property:
   736  
   737    A binary heap is a complete binary tree; that is, all levels of the tree, except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not complete, the nodes of that level are filled from left to right.
   738  - Heap property:
   739  
   740    All nodes are either greater than or equal to or less than or equal to each of its children, according to a comparison predicate defined for the heap. <sub><sup>[Wikipedia](http://en.wikipedia.org/wiki/Binary_heap)</sub></sup>
   741  
   742  Implements [Tree](#trees), [ReverseIteratorWithIndex](#reverseiteratorwithindex), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces.
   743  
   744  <p align="center"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Max-Heap.svg/501px-Max-Heap.svg.png" width="300px" height="200px" /></p>
   745  
   746  ```go
   747  package main
   748  
   749  import (
   750  	"github.com/alexandrestein/gods/trees/binaryheap"
   751  	"github.com/alexandrestein/gods/utils"
   752  )
   753  
   754  func main() {
   755  
   756  	// Min-heap
   757  	heap := binaryheap.NewWithIntComparator() // empty (min-heap)
   758  	heap.Push(2)                              // 2
   759  	heap.Push(3)                              // 2, 3
   760  	heap.Push(1)                              // 1, 3, 2
   761  	heap.Values()                             // 1, 3, 2
   762  	_, _ = heap.Peek()                        // 1,true
   763  	_, _ = heap.Pop()                         // 1, true
   764  	_, _ = heap.Pop()                         // 2, true
   765  	_, _ = heap.Pop()                         // 3, true
   766  	_, _ = heap.Pop()                         // nil, false (nothing to pop)
   767  	heap.Push(1)                              // 1
   768  	heap.Clear()                              // empty
   769  	heap.Empty()                              // true
   770  	heap.Size()                               // 0
   771  
   772  	// Max-heap
   773  	inverseIntComparator := func(a, b interface{}) int {
   774  		return -utils.IntComparator(a, b)
   775  	}
   776  	heap = binaryheap.NewWith(inverseIntComparator) // empty (min-heap)
   777  	heap.Push(2, 3, 1)                              // 3, 2, 1 (bulk optimized)
   778  	heap.Values()                                   // 3, 2, 1
   779  }
   780  ```
   781  
   782  ## Functions
   783  
   784  Various helper functions used throughout the library.
   785  
   786  ### Comparator
   787  
   788  Some data structures (e.g. TreeMap, TreeSet) require a comparator function to automatically keep their elements sorted upon insertion. This comparator is necessary during the initalization.
   789  
   790  Comparator is defined as:
   791  
   792  Return values (int):
   793  
   794  ```go
   795  negative , if a < b
   796  zero     , if a == b
   797  positive , if a > b
   798  ```
   799  
   800  Comparator signature:
   801  
   802  ```go
   803  type Comparator func(a, b interface{}) int
   804  ```
   805  
   806  All common comparators for builtin types are included in the library:
   807  
   808  ```go
   809  func StringComparator(a, b interface{}) int
   810  
   811  func IntComparator(a, b interface{}) int
   812  
   813  func Int8Comparator(a, b interface{}) int
   814  
   815  func Int16Comparator(a, b interface{}) int
   816  
   817  func Int32Comparator(a, b interface{}) int
   818  
   819  func Int64Comparator(a, b interface{}) int
   820  
   821  func UIntComparator(a, b interface{}) int
   822  
   823  func UInt8Comparator(a, b interface{}) int
   824  
   825  func UInt16Comparator(a, b interface{}) int
   826  
   827  func UInt32Comparator(a, b interface{}) int
   828  
   829  func UInt64Comparator(a, b interface{}) int
   830  
   831  func Float32Comparator(a, b interface{}) int
   832  
   833  func Float64Comparator(a, b interface{}) int
   834  
   835  func ByteComparator(a, b interface{}) int
   836  
   837  func RuneComparator(a, b interface{}) int
   838  
   839  func TimeComparator(a, b interface{}) int
   840  ```
   841  
   842  Writing custom comparators is easy:
   843  
   844  ```go
   845  package main
   846  
   847  import (
   848  	"fmt"
   849  	"github.com/alexandrestein/gods/sets/treeset"
   850  )
   851  
   852  type User struct {
   853  	id   int
   854  	name string
   855  }
   856  
   857  // Custom comparator (sort by IDs)
   858  func byID(a, b interface{}) int {
   859  
   860  	// Type assertion, program will panic if this is not respected
   861  	c1 := a.(User)
   862  	c2 := b.(User)
   863  
   864  	switch {
   865  	case c1.id > c2.id:
   866  		return 1
   867  	case c1.id < c2.id:
   868  		return -1
   869  	default:
   870  		return 0
   871  	}
   872  }
   873  
   874  func main() {
   875  	set := treeset.NewWith(byID)
   876  
   877  	set.Add(User{2, "Second"})
   878  	set.Add(User{3, "Third"})
   879  	set.Add(User{1, "First"})
   880  	set.Add(User{4, "Fourth"})
   881  
   882  	fmt.Println(set) // {1 First}, {2 Second}, {3 Third}, {4 Fourth}
   883  }
   884  ```
   885  
   886  ### Iterator
   887  
   888  All ordered containers have stateful iterators. Typically an iterator is obtained by _Iterator()_ function of an ordered container. Once obtained, iterator's _Next()_ function moves the iterator to the next element and returns true if there was a next element. If there was an element, then element's can be obtained by iterator's _Value()_ function. Depending on the ordering type, it's position can be obtained by iterator's _Index()_ or _Key()_ functions. Some containers even provide reversible iterators, essentially the same, but provide another extra _Prev()_ function that moves the iterator to the previous element and returns true if there was a previous element.
   889  
   890  Note: it is unsafe to remove elements from container while iterating.
   891  
   892  #### IteratorWithIndex
   893  
   894  An [iterator](#iterator) whose elements are referenced by an index.
   895  
   896  Typical usage:
   897  ```go
   898  it := list.Iterator()
   899  for it.Next() {
   900  	index, value := it.Index(), it.Value()
   901  	...
   902  }
   903  ```
   904  
   905  Other usages:
   906  ```go
   907  if it.First() {
   908  	firstIndex, firstValue := it.Index(), it.Value()
   909  	...
   910  }
   911  ```
   912  
   913  ```go
   914  for it.Begin(); it.Next(); {
   915  	...
   916  }
   917  ```
   918  
   919  #### IteratorWithKey
   920  
   921  An [iterator](#iterator) whose elements are referenced by a key.
   922  
   923  Typical usage:
   924  ```go
   925  it := tree.Iterator()
   926  for it.Next() {
   927  	key, value := it.Key(), it.Value()
   928  	...
   929  }
   930  ```
   931  
   932  Other usages:
   933  ```go
   934  if it.First() {
   935  	firstKey, firstValue := it.Key(), it.Value()
   936  	...
   937  }
   938  ```
   939  
   940  ```go
   941  for it.Begin(); it.Next(); {
   942  	...
   943  }
   944  ```
   945  
   946  #### ReverseIteratorWithIndex
   947  
   948  An [iterator](#iterator) whose elements are referenced by an index. Provides all functions as [IteratorWithIndex](#iteratorwithindex), but can also be used for reverse iteration.
   949  
   950  Typical usage of iteration in reverse:
   951  ```go
   952  it := list.Iterator()
   953  for it.End(); it.Prev(); {
   954  	index, value := it.Index(), it.Value()
   955  	...
   956  }
   957  ```
   958  
   959  Other usages:
   960  ```go
   961  if it.Last() {
   962  	lastIndex, lastValue := it.Index(), it.Value()
   963  	...
   964  }
   965  ```
   966  
   967  #### ReverseIteratorWithKey
   968  
   969  An [iterator](#iterator) whose elements are referenced by a key. Provides all functions as [IteratorWithKey](#iteratorwithkey), but can also be used for reverse iteration.
   970  
   971  Typical usage of iteration in reverse:
   972  ```go
   973  it := tree.Iterator()
   974  for it.End(); it.Prev(); {
   975  	key, value := it.Key(), it.Value()
   976  	...
   977  }
   978  ```
   979  
   980  Other usages:
   981  ```go
   982  if it.Last() {
   983  	lastKey, lastValue := it.Key(), it.Value()
   984  	...
   985  }
   986  ```
   987  
   988  ### Enumerable
   989  
   990  Enumerable functions for ordered containers that implement [EnumerableWithIndex](#enumerablewithindex) or [EnumerableWithKey](#enumerablewithkey) interfaces.
   991  
   992  #### EnumerableWithIndex
   993  
   994  [Enumerable](#enumerable) functions for ordered containers whose values can be fetched by an index.
   995  
   996  **Each**
   997  
   998  Calls the given function once for each element, passing that element's index and value.
   999  
  1000  ```go
  1001  Each(func(index int, value interface{}))
  1002  ```
  1003  
  1004  **Map**
  1005  
  1006  Invokes the given function once for each element and returns a container containing the values returned by the given function.
  1007  
  1008  ```go
  1009  Map(func(index int, value interface{}) interface{}) Container
  1010  ```
  1011  
  1012  **Select**
  1013  
  1014  Returns a new container containing all elements for which the given function returns a true value.
  1015  
  1016  ```go
  1017  Select(func(index int, value interface{}) bool) Container
  1018  ```
  1019  
  1020  **Any**
  1021  
  1022  Passes each element of the container to the given function and returns true if the function ever returns true for any element.
  1023  
  1024  ```go
  1025  Any(func(index int, value interface{}) bool) bool
  1026  ```
  1027  
  1028  **All**
  1029  
  1030  Passes each element of the container to the given function and returns true if the function returns true for all elements.
  1031  
  1032  ```go
  1033  All(func(index int, value interface{}) bool) bool
  1034  ```
  1035  
  1036  **Find**
  1037  
  1038  Passes each element of the container to the given function and returns the first (index,value) for which the function is true or -1,nil otherwise if no element matches the criteria.
  1039  
  1040  ```go
  1041  Find(func(index int, value interface{}) bool) (int, interface{})}
  1042  ```
  1043  
  1044  **Example:**
  1045  
  1046  ```go
  1047  package main
  1048  
  1049  import (
  1050  	"fmt"
  1051  	"github.com/alexandrestein/gods/sets/treeset"
  1052  )
  1053  
  1054  func printSet(txt string, set *treeset.Set) {
  1055  	fmt.Print(txt, "[ ")
  1056  	set.Each(func(index int, value interface{}) {
  1057  		fmt.Print(value, " ")
  1058  	})
  1059  	fmt.Println("]")
  1060  }
  1061  
  1062  func main() {
  1063  	set := treeset.NewWithIntComparator()
  1064  	set.Add(2, 3, 4, 2, 5, 6, 7, 8)
  1065  	printSet("Initial", set) // [ 2 3 4 5 6 7 8 ]
  1066  
  1067  	even := set.Select(func(index int, value interface{}) bool {
  1068  		return value.(int)%2 == 0
  1069  	})
  1070  	printSet("Even numbers", even) // [ 2 4 6 8 ]
  1071  
  1072  	foundIndex, foundValue := set.Find(func(index int, value interface{}) bool {
  1073  		return value.(int)%2 == 0 && value.(int)%3 == 0
  1074  	})
  1075  	if foundIndex != -1 {
  1076  		fmt.Println("Number divisible by 2 and 3 found is", foundValue, "at index", foundIndex) // value: 6, index: 4
  1077  	}
  1078  
  1079  	square := set.Map(func(index int, value interface{}) interface{} {
  1080  		return value.(int) * value.(int)
  1081  	})
  1082  	printSet("Numbers squared", square) // [ 4 9 16 25 36 49 64 ]
  1083  
  1084  	bigger := set.Any(func(index int, value interface{}) bool {
  1085  		return value.(int) > 5
  1086  	})
  1087  	fmt.Println("Set contains a number bigger than 5 is ", bigger) // true
  1088  
  1089  	positive := set.All(func(index int, value interface{}) bool {
  1090  		return value.(int) > 0
  1091  	})
  1092  	fmt.Println("All numbers are positive is", positive) // true
  1093  
  1094  	evenNumbersSquared := set.Select(func(index int, value interface{}) bool {
  1095  		return value.(int)%2 == 0
  1096  	}).Map(func(index int, value interface{}) interface{} {
  1097  		return value.(int) * value.(int)
  1098  	})
  1099  	printSet("Chaining", evenNumbersSquared) // [ 4 16 36 64 ]
  1100  }
  1101  ```
  1102  
  1103  #### EnumerableWithKey
  1104  
  1105  Enumerable functions for ordered containers whose values whose elements are key/value pairs.
  1106  
  1107  **Each**
  1108  
  1109  Calls the given function once for each element, passing that element's key and value.
  1110  
  1111  ```go
  1112  Each(func(key interface{}, value interface{}))
  1113  ```
  1114  
  1115  **Map**
  1116  
  1117  Invokes the given function once for each element and returns a container containing the values returned by the given function as key/value pairs.
  1118  
  1119  ```go
  1120  Map(func(key interface{}, value interface{}) (interface{}, interface{})) Container
  1121  ```
  1122  
  1123  **Select**
  1124  
  1125  Returns a new container containing all elements for which the given function returns a true value.
  1126  
  1127  ```go
  1128  Select(func(key interface{}, value interface{}) bool) Container
  1129  ```
  1130  
  1131  **Any**
  1132  
  1133  Passes each element of the container to the given function and returns true if the function ever returns true for any element.
  1134  
  1135  ```go
  1136  Any(func(key interface{}, value interface{}) bool) bool
  1137  ```
  1138  
  1139  **All**
  1140  
  1141  Passes each element of the container to the given function and returns true if the function returns true for all elements.
  1142  
  1143  ```go
  1144  All(func(key interface{}, value interface{}) bool) bool
  1145  ```
  1146  
  1147  **Find**
  1148  
  1149  Passes each element of the container to the given function and returns the first (key,value) for which the function is true or nil,nil otherwise if no element matches the criteria.
  1150  
  1151  ```go
  1152  Find(func(key interface{}, value interface{}) bool) (interface{}, interface{})
  1153  ```
  1154  
  1155  **Example:**
  1156  
  1157  ```go
  1158  package main
  1159  
  1160  import (
  1161  	"fmt"
  1162  	"github.com/alexandrestein/gods/maps/treemap"
  1163  )
  1164  
  1165  func printMap(txt string, m *treemap.Map) {
  1166  	fmt.Print(txt, " { ")
  1167  	m.Each(func(key interface{}, value interface{}) {
  1168  		fmt.Print(key, ":", value, " ")
  1169  	})
  1170  	fmt.Println("}")
  1171  }
  1172  
  1173  func main() {
  1174  	m := treemap.NewWithStringComparator()
  1175  	m.Put("g", 7)
  1176  	m.Put("f", 6)
  1177  	m.Put("e", 5)
  1178  	m.Put("d", 4)
  1179  	m.Put("c", 3)
  1180  	m.Put("b", 2)
  1181  	m.Put("a", 1)
  1182  	printMap("Initial", m) // { a:1 b:2 c:3 d:4 e:5 f:6 g:7 }
  1183  
  1184  	even := m.Select(func(key interface{}, value interface{}) bool {
  1185  		return value.(int) % 2 == 0
  1186  	})
  1187  	printMap("Elements with even values", even) // { b:2 d:4 f:6 }
  1188  
  1189  	foundKey, foundValue := m.Find(func(key interface{}, value interface{}) bool {
  1190  		return value.(int) % 2 == 0 && value.(int) % 3 == 0
  1191  	})
  1192  	if foundKey != nil {
  1193  		fmt.Println("Element with value divisible by 2 and 3 found is", foundValue, "with key", foundKey) // value: 6, index: 4
  1194  	}
  1195  
  1196  	square := m.Map(func(key interface{}, value interface{}) (interface{}, interface{}) {
  1197  		return key.(string) + key.(string), value.(int) * value.(int)
  1198  	})
  1199  	printMap("Elements' values squared and letters duplicated", square) // { aa:1 bb:4 cc:9 dd:16 ee:25 ff:36 gg:49 }
  1200  
  1201  	bigger := m.Any(func(key interface{}, value interface{}) bool {
  1202  		return value.(int) > 5
  1203  	})
  1204  	fmt.Println("Map contains element whose value is bigger than 5 is", bigger) // true
  1205  
  1206  	positive := m.All(func(key interface{}, value interface{}) bool {
  1207  		return value.(int) > 0
  1208  	})
  1209  	fmt.Println("All map's elements have positive values is", positive) // true
  1210  
  1211  	evenNumbersSquared := m.Select(func(key interface{}, value interface{}) bool {
  1212  		return value.(int) % 2 == 0
  1213  	}).Map(func(key interface{}, value interface{}) (interface{}, interface{}) {
  1214  		return key, value.(int) * value.(int)
  1215  	})
  1216  	printMap("Chaining", evenNumbersSquared) // { b:4 d:16 f:36 }
  1217  }
  1218  ```
  1219  
  1220  ### Serialization
  1221  
  1222  All data structures can be serialized (marshalled) and deserialized (unmarshalled). Currently only JSON support is available.
  1223  
  1224  #### JSONSerializer
  1225  
  1226  Outputs the container into its JSON representation.
  1227  
  1228  Typical usage for key-value structures:
  1229  ```go
  1230  package main
  1231  
  1232  import (
  1233  	"fmt"
  1234  	"github.com/alexandrestein/gods/maps/hashmap"
  1235  )
  1236  
  1237  func main() {
  1238  	m := hashmap.New()
  1239  	m.Put("a", "1")
  1240  	m.Put("b", "2")
  1241  	m.Put("c", "3")
  1242  
  1243  	json, err := m.ToJSON()
  1244  	if err != nil {
  1245  		fmt.Println(err)
  1246  	}
  1247  	fmt.Println(string(json)) // {"a":"1","b":"2","c":"3"}
  1248  ```
  1249  
  1250  Typical usage for value-only structures:
  1251  ```go
  1252  package main
  1253  
  1254  import (
  1255  	"fmt"
  1256  	"github.com/alexandrestein/gods/lists/arraylist"
  1257  )
  1258  
  1259  func main() {
  1260  	list := arraylist.New()
  1261  	list.Add("a", "b", "c")
  1262  
  1263  	json, err := list.ToJSON()
  1264  	if err != nil {
  1265  		fmt.Println(err)
  1266  	}
  1267  	fmt.Println(string(json)) // ["a","b","c"]
  1268  }
  1269  ```
  1270  
  1271  #### JSONDeserializer
  1272  
  1273  Populates the container with elements from the input JSON representation.
  1274  
  1275  Typical usage for key-value structures:
  1276  ```go
  1277  package main
  1278  
  1279  import (
  1280  	"fmt"
  1281  	"github.com/alexandrestein/gods/lists/arraylist"
  1282  )
  1283  
  1284  func main() {
  1285  	list := arraylist.New()
  1286  
  1287  	json := []byte(`["a","b"]`)
  1288  	err := list.FromJSON(json)
  1289  	if err != nil {
  1290  		fmt.Println(err)
  1291  	}
  1292  	fmt.Println(list) // ArrayList ["a","b"]
  1293  }
  1294  ```
  1295  
  1296  Typical usage for value-only structures:
  1297  ```go
  1298  package main
  1299  
  1300  import (
  1301  	"fmt"
  1302  	"github.com/alexandrestein/gods/lists/arraylist"
  1303  )
  1304  
  1305  func main() {
  1306  	list := arraylist.New()
  1307  
  1308  	json := []byte(`["a","b"]`)
  1309  	err := list.FromJSON(json)
  1310  	if err != nil {
  1311  		fmt.Println(err)
  1312  	}
  1313  	fmt.Println(list) // ArrayList ["a","b"]
  1314  }
  1315  ```
  1316  
  1317  ### Sort
  1318  
  1319  Sort is a general purpose sort function.
  1320  
  1321  Lists have an in-place _Sort()_ function and all containers can return their sorted elements via _containers.GetSortedValues()_ function.
  1322  
  1323  Internally these all use the _utils.Sort()_ method:
  1324  
  1325  ```go
  1326  package main
  1327  
  1328  import "github.com/alexandrestein/gods/utils"
  1329  
  1330  func main() {
  1331  	strings := []interface{}{}                  // []
  1332  	strings = append(strings, "d")              // ["d"]
  1333  	strings = append(strings, "a")              // ["d","a"]
  1334  	strings = append(strings, "b")              // ["d","a",b"
  1335  	strings = append(strings, "c")              // ["d","a",b","c"]
  1336  	utils.Sort(strings, utils.StringComparator) // ["a","b","c","d"]
  1337  }
  1338  ```
  1339  
  1340  ### Container
  1341  
  1342  Container specific operations:
  1343  
  1344  ```go
  1345  // Returns sorted container''s elements with respect to the passed comparator.
  1346  // Does not effect the ordering of elements within the container.
  1347  func GetSortedValues(container Container, comparator utils.Comparator) []interface{}
  1348  ```
  1349  
  1350  Usage:
  1351  
  1352  ```go
  1353  package main
  1354  
  1355  import (
  1356  	"github.com/alexandrestein/gods/lists/arraylist"
  1357  	"github.com/alexandrestein/gods/utils"
  1358  )
  1359  
  1360  func main() {
  1361  	list := arraylist.New()
  1362  	list.Add(2, 1, 3)
  1363  	values := GetSortedValues(container, utils.StringComparator) // [1, 2, 3]
  1364  }
  1365  ```
  1366  
  1367  ## Appendix
  1368  
  1369  ### Motivation
  1370  
  1371  Collections and data structures found in other languages: Java Collections, C++ Standard Template Library (STL) containers, Qt Containers, Ruby Enumerable etc.
  1372  
  1373  ### Goals
  1374  
  1375  **Fast algorithms**:
  1376  
  1377    - Based on decades of knowledge and experiences of other libraries mentioned above.
  1378  
  1379  **Memory efficient algorithms**:
  1380  
  1381    - Avoiding to consume memory by using optimal algorithms and data structures for the given set of problems, e.g. red-black tree in case of TreeMap to avoid keeping redundant sorted array of keys in memory.
  1382  
  1383  **Easy to use library**:
  1384  
  1385    - Well-structured library with minimalistic set of atomic operations from which more complex operations can be crafted.
  1386  
  1387  **Stable library**:
  1388  
  1389    - Only additions are permitted keeping the library backward compatible.
  1390  
  1391  **Solid documentation and examples**:
  1392  
  1393    - Learning by example.
  1394  
  1395  **Production ready**:
  1396  
  1397    - Used in production.
  1398  
  1399  **No dependencies**:
  1400  
  1401    - No external imports.
  1402  
  1403  There is often a tug of war between speed and memory when crafting algorithms. We choose to optimize for speed in most cases within reasonable limits on memory consumption.
  1404  
  1405  Thread safety is not a concern of this project, this should be handled at a higher level.
  1406  
  1407  ### Testing and Benchmarking
  1408  
  1409  This takes a while, so test within sub-packages:
  1410  
  1411  `go test -run=NO_TEST -bench . -benchmem  -benchtime 1s ./...`
  1412  
  1413  <p align="center"><img src="https://cloud.githubusercontent.com/assets/3115942/16892979/5e698d46-4b27-11e6-864b-cb2b865327b6.png" /></p>
  1414  
  1415  ### Contributing
  1416  
  1417  Biggest contribution towards this library is to use it and give us feedback for further improvements and additions.
  1418  
  1419  For direct contributions, _pull request_ into master branch or ask to become a contributor.
  1420  
  1421  Coding style:
  1422  
  1423  ```shell
  1424  # Install tooling and set path:
  1425  go get github.com/golang/lint/golint
  1426  go get github.com/fzipp/gocyclo
  1427  go get github.com/kisielk/errcheck
  1428  export PATH=$PATH:$GOPATH/bin
  1429  
  1430  # Fix errors and warnings:
  1431  go fmt ./... && gofmt -s -w . && go vet ./... && go get ./... && go test ./... && golint ./... && gocyclo -avg -over 15 . && errcheck ./...
  1432  ```
  1433  
  1434  ### License
  1435  
  1436  This library is distributed under the BSD-style license found in the [LICENSE](https://github.com/alexandrestein/gods/blob/master/LICENSE) file.
  1437  
  1438  ### Sponsors
  1439  
  1440  ## <a href="https://www.browserstack.com/?ref=gods"><img src="http://www.hajdarevic.net/browserstack.svg" alt="BrowserStack" width="250"/></a>
  1441  [BrowserStack](https://www.browserstack.com/?ref=webhook) is a cloud-based cross-browser testing tool that enables developers to test their websites across various browsers on different operating systems and mobile devices, without requiring users to install virtual machines, devices or emulators.