Files
servicebase/pkg/tools/list.go
2025-11-18 17:48:20 +08:00

27 lines
601 B
Go

package tools
func ListToMap[K comparable, S any](list []S, keyFunc func(S) K) map[K]S {
if len(list) == 0 {
return make(map[K]S)
}
result := make(map[K]S, len(list))
for _, item := range list {
key := keyFunc(item)
result[key] = item
}
return result
}
func SliceToMapList[K comparable, V any](slice []V, keyFunc func(V) K) map[K][]V {
result := make(map[K][]V)
for _, v := range slice {
key := keyFunc(v)
if _, ok := result[key]; !ok {
result[key] = make([]V, 0)
result[key] = append(result[key], v)
} else {
result[key] = append(result[key], v)
}
}
return result
}