github.com/enetx/g@v1.0.80/examples/slices/slice_of_slices.go (about) 1 package main 2 3 import ( 4 "fmt" 5 6 "github.com/enetx/g" 7 "github.com/enetx/g/cmp" 8 ) 9 10 func main() { 11 ns1 := g.NewSlice[g.String]().Append("aaa") 12 ns2 := g.NewSlice[g.String]().Append("bbb", "ccc") 13 ns3 := g.NewSlice[g.String]().Append("ccc", "dddd", "wwwww") 14 15 nx := g.SliceOf(ns3, ns2, ns1, ns2) 16 17 nx.SortBy(func(a, b g.Slice[g.String]) cmp.Ordering { 18 if a.Eq(b) { 19 return cmp.Equal 20 } 21 22 return cmp.Less 23 }) 24 25 nx.Print() 26 27 nx = nx.Iter().Dedup().Collect().Print() 28 29 nx.SortBy(func(a, b g.Slice[g.String]) cmp.Ordering { return b.Get(0).Cmp(a.Get(0)) }) 30 nx.Print() 31 32 nx.SortBy(func(a, b g.Slice[g.String]) cmp.Ordering { return a.Len().Cmp(b.Len()) }) 33 nx.Print() 34 35 nx.Reverse() 36 nx.Print() 37 38 nx.Random().Print() 39 nx.RandomSample(2).Print() 40 41 ch := nx.Iter().Chunks(2).Collect() // return []Slice[T] 42 chunks := g.SliceOf(ch...) // make slice chunks 43 chunks.Print() 44 45 // pr := nx.Iter().Permutations().Collect() // return []Slice[T] 46 // permutations := g.SliceOf(pr...) // make slice permutations 47 // permutations.Print() 48 49 m := g.NewMap[string, g.Slice[g.Slice[g.String]]]() 50 m.Set("one", nx) 51 52 fmt.Println(m.Get("one").Some().Last().Contains("aaa")) 53 54 nested := g.Slice[any]{1, 2, g.Slice[int]{3, 4, 5}, []any{6, 7, []int{8, 9}}} 55 flattened := nested.Iter().Flatten().Collect() 56 fmt.Println(flattened) 57 58 nestedSlice := g.Slice[any]{ 59 1, 60 g.SliceOf(2, 3), 61 "abc", 62 g.SliceOf("def", "ghi"), 63 g.SliceOf(4.5, 6.7), 64 } 65 66 nestedSlice.Print() // Output: Slice[1, Slice[2, 3], abc, Slice[def, ghi], Slice[4.5, 6.7]] 67 nestedSlice.Iter().Flatten().Collect().Print() // Output: Slice[1, 2, 3, abc, def, ghi, 4.5, 6.7] 68 69 nestedSlice2 := g.Slice[any]{ 70 1, 71 g.SliceOf(2, 3), 72 "abc", 73 g.SliceOf("awe", "som", "e"), 74 g.SliceOf("co", "ol"), 75 g.SliceOf(4.5, 6.7), 76 map[string]string{"a": "ss"}, 77 g.SliceOf(g.MapOrd[int, int]{{1, 1}}, g.MapOrd[int, int]{{2, 2}}), 78 } 79 80 nestedSlice2.Iter().Flatten().Collect().Print() 81 }