github.com/enetx/g@v1.0.80/examples/iter/iter_filter.go (about) 1 package main 2 3 import ( 4 "github.com/enetx/g" 5 "github.com/enetx/g/f" 6 ) 7 8 func main() { 9 // Example 1: Filter integers in a slice and print the result 10 g.SliceOf(1, 2). 11 Iter(). 12 // Filter(func(i int) bool { return i != 1 }). 13 // Filter(f.Ne(1)). 14 Filter(f.Ne(1)). 15 Collect(). 16 Print() // Slice[2] 17 18 // Example 2: Chained filtering on a slice of strings and print the result 19 fi := g.SliceOf("bbb", "ddd", "xxx", "aaa", "ccc").Iter() 20 21 fi = fi.Filter(f.Ne("aaa")) 22 fi = fi.Filter(f.Ne("xxx")) 23 fi = fi.Filter(f.Ne("ddd")) 24 fi = fi.Filter(f.Ne("bbb")) 25 26 // fi = fi.Filter(func(s string) bool { return s != "aaa" }) 27 // fi = fi.Filter(func(s string) bool { return s != "xxx" }) 28 // fi = fi.Filter(func(s string) bool { return s != "ddd" }) 29 // fi = fi.Filter(func(s string) bool { return s != "bbb" }) 30 31 fi.Collect().Print() // Slice[ccc] 32 33 // Example 3: Exclude a key from a map and print the result 34 g.NewMap[int, string]().Set(88, "aa").Set(99, "bb").Set(199, "ii"). 35 Iter(). 36 Exclude(func(k int, _ string) bool { return k == 99 }). 37 Collect(). 38 Print() // Map{88:aa, 199:ii} 39 40 // Example 4: Exclude empty strings from a slice and print the result 41 g.SliceOf[g.String]("", "bbb", "ddd", "", "aaa", "ccc"). 42 Iter(). 43 Exclude(f.Zero). 44 Collect(). 45 Print() // Slice[bbb, ddd, aaa, ccc] 46 }