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