Golang map 常用方法

文章目录

        • 前言
        • 按key排序
        • 按value排序
        • 统计字符串中元素重复出现次数并将结果排序返回

前言

由于map是无序的,所以排序成 slice 返回,且都使用泛,代码只是示例,省略了错误判断

按key排序

package main

import "fmt"

func example[T comparable, S any](source map[T]S, assert func(a, b T) bool) []S {
	var (
		i []T
		j []S
	)

	for k, _ := range source {
		i = append(i, k)
	}

	result := sort(i, assert)
	for _, k := range result {
		j = append(j, source[k])
	}
	return j
}

func sort[T any](source []T, assert func(a, b T) bool) []T {
	for i := 0; i < len(source); i++ {
		for j := i + 1; j < len(source); j++ {
			if assert(source[i], source[j]) {
				source[j], source[i] = source[i], source[j]
			}
		}
	}
	return source
}

func main() {
	s := example(map[int]string{2: "b", 1: "a", 3: "c"}, func(a, b int) bool {
		return a > b
	})
	fmt.Println(s) //[c,b,a]
}

按value排序

package main

import "fmt"

func example[T comparable, S any](source map[T]S, assert func(a, b S) bool) []S {
	var (
		i []S
	)

	for _, v := range source {
		i = append(i, v)
	}

	return sort(i, assert)
}

func sort[T any](source []T, assert func(a, b T) bool) []T {
	for i := 0; i < len(source); i++ {
		for j := i + 1; j < len(source); j++ {
			if assert(source[i], source[j]) {
				source[j], source[i] = source[i], source[j]
			}
		}
	}
	return source
}

func main() {
	s := example(map[int]int{3: 2, 2: 1, 1: 3}, func(a, b int) bool {
		return a > b
	})
	fmt.Println(s)
}

统计字符串中元素重复出现次数并将结果排序返回

package main

import "fmt"

type count struct {
	value string
	count int
}

func example(s string) []count {
	var countSlice []count
	m := make(map[string]int, len(s))
	for _, char := range s {
		m[string(char)]++
	}

	for k, v := range m {
		countSlice = append(countSlice, count{count: v, value: k})
	}

	return sort(countSlice, func(a, b count) bool {
		return a.count > b.count
	})
}

func sort[T any](source []T, assert func(a, b T) bool) []T {
	for i := 0; i < len(source); i++ {
		for j := i + 1; j < len(source); j++ {
			if assert(source[i], source[j]) {
				source[j], source[i] = source[i], source[j]
			}
		}
	}
	return source
}

func main() {
	s := example("abaabccccc")
	fmt.Println(s) //[{b 2} {a 3} {c 5}]
}

你可能感兴趣的:(Golang,#,go从入门到精通,golang,开发语言,后端)