Debian Codegraph @

examples/iteratorwithkey/iteratorwithkey.go

raw symbols SCIP
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 "strings"
10
11 "github.com/emirpasic/gods/v2/maps/treemap"
12 )
13
14 // IteratorWithKeyExample to demonstrate basic usage of IteratorWithKey
15 func main() {
16 m := treemap.New[int, string]()
17 m.Put(0, "a")
18 m.Put(1, "b")
19 m.Put(2, "c")
20 it := m.Iterator()
21
22 fmt.Print("\nForward iteration\n")
23 for it.Next() {
24 key, value := it.Key(), it.Value()
25 fmt.Print("[", key, ":", value, "]") // [0:a][1:b][2:c]
26 }
27
28 fmt.Print("\nForward iteration (again)\n")
29 for it.Begin(); it.Next(); {
30 key, value := it.Key(), it.Value()
31 fmt.Print("[", key, ":", value, "]") // [0:a][1:b][2:c]
32 }
33
34 fmt.Print("\nBackward iteration\n")
35 for it.Prev() {
36 key, value := it.Key(), it.Value()
37 fmt.Print("[", key, ":", value, "]") // [2:c][1:b][0:a]
38 }
39
40 fmt.Print("\nBackward iteration (again)\n")
41 for it.End(); it.Prev(); {
42 key, value := it.Key(), it.Value()
43 fmt.Print("[", key, ":", value, "]") // [2:c][1:b][0:a]
44 }
45
46 if it.First() {
47 fmt.Print("\nFirst key: ", it.Key()) // First key: 0
48 fmt.Print("\nFirst value: ", it.Value()) // First value: a
49 }
50
51 if it.Last() {
52 fmt.Print("\nLast key: ", it.Key()) // Last key: 2
53 fmt.Print("\nLast value: ", it.Value()) // Last value: c
54 }
55
56 // Seek key-value pair whose value starts with "b"
57 seek := func(key int, value string) bool {
58 return strings.HasSuffix(value, "b")
59 }
60
61 it.Begin()
62 for found := it.NextTo(seek); found; found = it.Next() {
63 fmt.Print("\nNextTo key: ", it.Key())
64 fmt.Print("\nNextTo value: ", it.Value())
65 } /*
66 NextTo key: 1
67 NextTo value: "b"
68 NextTo key: 2
69 NextTo value: "c"
70 */
71
72 it.End()
73 for found := it.PrevTo(seek); found; found = it.Prev() {
74 fmt.Print("\nNextTo key: ", it.Key())
75 fmt.Print("\nNextTo value: ", it.Value())
76 } /*
77 NextTo key: 1
78 NextTo value: "b"
79 NextTo key: 0
80 NextTo value: "a"
81 */
82 }