Debian Codegraph @

examples/enumerablewithindex/enumerablewithindex.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/sets/treeset"
11 )
12
13 func printSet(txt string, set *treeset.Set[int]) {
14 fmt.Print(txt, "[ ")
15 set.Each(func(index int, value int) {
16 fmt.Print(value, " ")
17 })
18 fmt.Println("]")
19 }
20
21 // EnumerableWithIndexExample to demonstrate basic usage of EnumerableWithIndex
22 func main() {
23 set := treeset.New[int]()
24 set.Add(2, 3, 4, 2, 5, 6, 7, 8)
25 printSet("Initial", set) // [ 2 3 4 5 6 7 8 ]
26
27 even := set.Select(func(index int, value int) bool {
28 return value%2 == 0
29 })
30 printSet("Even numbers", even) // [ 2 4 6 8 ]
31
32 foundIndex, foundValue := set.Find(func(index int, value int) bool {
33 return value%2 == 0 && value%3 == 0
34 })
35 if foundIndex != -1 {
36 fmt.Println("Number divisible by 2 and 3 found is", foundValue, "at index", foundIndex) // value: 6, index: 4
37 }
38
39 square := set.Map(func(index int, value int) int {
40 return value * value
41 })
42 printSet("Numbers squared", square) // [ 4 9 16 25 36 49 64 ]
43
44 bigger := set.Any(func(index int, value int) bool {
45 return value > 5
46 })
47 fmt.Println("Set contains a number bigger than 5 is ", bigger) // true
48
49 positive := set.All(func(index int, value int) bool {
50 return value > 0
51 })
52 fmt.Println("All numbers are positive is", positive) // true
53
54 evenNumbersSquared := set.Select(func(index int, value int) bool {
55 return value%2 == 0
56 }).Map(func(index int, value int) int {
57 return value * value
58 })
59 printSet("Chaining", evenNumbersSquared) // [ 4 16 36 64 ]
60 }