Comparator

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.

Comparator is defined as:

Return values (int):

  1. negative , if a < b
  2. zero , if a == b
  3. positive , if a > b

Comparator signature:

  1. type Comparator func(a, b interface{}) int

All common comparators for builtin types are included in the library:

  1. func StringComparator(a, b interface{}) int
  2. func IntComparator(a, b interface{}) int
  3. func Int8Comparator(a, b interface{}) int
  4. func Int16Comparator(a, b interface{}) int
  5. func Int32Comparator(a, b interface{}) int
  6. func Int64Comparator(a, b interface{}) int
  7. func UIntComparator(a, b interface{}) int
  8. func UInt8Comparator(a, b interface{}) int
  9. func UInt16Comparator(a, b interface{}) int
  10. func UInt32Comparator(a, b interface{}) int
  11. func UInt64Comparator(a, b interface{}) int
  12. func Float32Comparator(a, b interface{}) int
  13. func Float64Comparator(a, b interface{}) int
  14. func ByteComparator(a, b interface{}) int
  15. func RuneComparator(a, b interface{}) int
  16. func TimeComparator(a, b interface{}) int

Writing custom comparators is easy:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/emirpasic/gods/sets/treeset"
  5. )
  6. type User struct {
  7. id int
  8. name string
  9. }
  10. // Custom comparator (sort by IDs)
  11. func byID(a, b interface{}) int {
  12. // Type assertion, program will panic if this is not respected
  13. c1 := a.(User)
  14. c2 := b.(User)
  15. switch {
  16. case c1.id > c2.id:
  17. return 1
  18. case c1.id < c2.id:
  19. return -1
  20. default:
  21. return 0
  22. }
  23. }
  24. func main() {
  25. set := treeset.NewWith(byID)
  26. set.Add(User{2, "Second"})
  27. set.Add(User{3, "Third"})
  28. set.Add(User{1, "First"})
  29. set.Add(User{4, "Fourth"})
  30. fmt.Println(set) // {1 First}, {2 Second}, {3 Third}, {4 Fourth}
  31. }