Golang map 常用方法

前言

由于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}]
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值