github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/container/sort_map/example_sort_map_test.go (about) 1 package sort_map 2 3 import ( 4 "fmt" 5 "sort" 6 ) 7 8 func wordCnSortByChar(longStr string) { 9 mapChars := make(map[byte]int) 10 chars := make([]int, 0, len(longStr)) 11 for _, c := range longStr { 12 if _, ok := mapChars[byte(c)]; !ok { 13 chars = append(chars, int(c)) 14 } 15 mapChars[byte(c)]++ 16 } 17 for k, v := range mapChars { 18 println(k, v) 19 } 20 21 sort.Ints(chars) 22 /* 23 sort.Slice(chars, func(i, j int) bool { 24 if chars[i] < chars[j] { 25 return true 26 } 27 return false 28 }) 29 */ 30 println() 31 for _, char := range chars { 32 fmt.Println(fmt.Sprintf("%s", []byte{byte(char)}), mapChars[byte(char)]) 33 } 34 } 35 36 func wordCnSortByCharSlice(longStr string) { 37 mapChars := make(map[int64]int64) 38 for _, c := range longStr { 39 mapChars[int64(c)]++ 40 } 41 for k, v := range mapChars { 42 println(k, v) 43 } 44 println() 45 sliceKVChars := SortIntIntMapByKey(mapChars) 46 for _, item := range sliceKVChars { 47 fmt.Println(fmt.Sprintf("%s", []byte{byte(item.Key)}), item.Value) 48 } 49 } 50 51 func ExampleSortIntIntMapByKey() { 52 longStr := "aabbccddddca" 53 wordCnSortByChar(longStr) 54 wordCnSortByCharSlice(longStr) 55 // Output: 56 // a 3 57 // b 2 58 // c 3 59 // d 4 60 // a 3 61 // b 2 62 // c 3 63 // d 4 64 }