Debian Codegraph @

examples/enumerablewithkey/enumerablewithkey.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
10 "github.com/emirpasic/gods/v2/maps/treemap"
11 )
12
13 func printMap(txt string, m *treemap.Map[string, int]) {
14 fmt.Print(txt, " { ")
15 m.Each(func(key string, value int) {
16 fmt.Print(key, ":", value, " ")
17 })
18 fmt.Println("}")
19 }
20
21 // EunumerableWithKeyExample to demonstrate basic usage of EunumerableWithKey
22 func main() {
23 m := treemap.New[string, int]()
24 m.Put("g", 7)
25 m.Put("f", 6)
26 m.Put("e", 5)
27 m.Put("d", 4)
28 m.Put("c", 3)
29 m.Put("b", 2)
30 m.Put("a", 1)
31 printMap("Initial", m) // { a:1 b:2 c:3 d:4 e:5 f:6 g:7 }
32
33 even := m.Select(func(key string, value int) bool {
34 return value%2 == 0
35 })
36 printMap("Elements with even values", even) // { b:2 d:4 f:6 }
37
38 foundKey, foundValue := m.Find(func(key string, value int) bool {
39 return value%2 == 0 && value%3 == 0
40 })
41 if foundKey != "" {
42 fmt.Println("Element with value divisible by 2 and 3 found is", foundValue, "with key", foundKey) // value: 6, index: 4
43 }
44
45 square := m.Map(func(key string, value int) (string, int) {
46 return key + key, value * value
47 })
48 printMap("Elements' values squared and letters duplicated", square) // { aa:1 bb:4 cc:9 dd:16 ee:25 ff:36 gg:49 }
49
50 bigger := m.Any(func(key string, value int) bool {
51 return value > 5
52 })
53 fmt.Println("Map contains element whose value is bigger than 5 is", bigger) // true
54
55 positive := m.All(func(key string, value int) bool {
56 return value > 0
57 })
58 fmt.Println("All map's elements have positive values is", positive) // true
59
60 evenNumbersSquared := m.Select(func(key string, value int) bool {
61 return value%2 == 0
62 }).Map(func(key string, value int) (string, int) {
63 return key, value * value
64 })
65 printMap("Chaining", evenNumbersSquared) // { b:4 d:16 f:36 }
66 }