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