github.com/mymmsc/gox@v1.3.33/util/examples/iteratorwithkey/iteratorwithkey.go (about) 1 // Copyright (c) 2015, Emir Pasic. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "fmt" 9 "github.com/mymmsc/gox/util/treemap" 10 ) 11 12 // IteratorWithKeyExample to demonstrate basic usage of IteratorWithKey 13 func main() { 14 m := treemap.NewWithIntComparator() 15 m.Put(1, "a") 16 m.Put(2, "b") 17 m.Put(3, "a") 18 it := m.Iterator() 19 20 fmt.Print("\nForward iteration\n") 21 for it.Next() { 22 key, value := it.Key(), it.Value() 23 fmt.Print("[", key, ":", value, "]") // [0:a][1:b][2:c] 24 } 25 26 fmt.Print("\nForward iteration (again)\n") 27 for it.Begin(); it.Next(); { 28 key, value := it.Key(), it.Value() 29 fmt.Print("[", key, ":", value, "]") // [0:a][1:b][2:c] 30 } 31 32 fmt.Print("\nBackward iteration\n") 33 for it.Prev() { 34 key, value := it.Key(), it.Value() 35 fmt.Print("[", key, ":", value, "]") // [2:c][1:b][0:a] 36 } 37 38 fmt.Print("\nBackward iteration (again)\n") 39 for it.End(); it.Prev(); { 40 key, value := it.Key(), it.Value() 41 fmt.Print("[", key, ":", value, "]") // [2:c][1:b][0:a] 42 } 43 44 if it.First() { 45 fmt.Print("\nFirst key: ", it.Key()) // First key: 0 46 fmt.Print("\nFirst value: ", it.Value()) // First value: a 47 } 48 49 if it.Last() { 50 fmt.Print("\nLast key: ", it.Key()) // Last key: 3 51 fmt.Print("\nLast value: ", it.Value()) // Last value: c 52 } 53 }