How to sort map in Go in descending order?
Example:
map[string]int{"value1": 10, "value2": 20,"value3": 30} Well, look, you can convert map to an array of a certain structure []struct and therefore use the function sort.Slice .
m := map[string]int{"value1": 10, "value2": 20,"value3": 30} type key_value struct { Key string Value int } var sorted_struct []key_value for key, value := range m { sorted_struct = append(sorted_struct , key_value {key, value}) } sort.Slice(sorted_struct , func(i, j int) bool { return sorted_struct[i].Value > sorted_struct[j].Value }) for _, key_value := range sorted_struct { fmt.Printf("%s, %d\n", key_value.Key, key_value.Value) } //OUTPUT: //value3, 30 //value2, 20 //value1, 10 You can convert a sorted array of a certain structure to a map as follows.
[]struct to map yourMap := structs.Map(sortedStructArray) But for this you need to connect the packet structs .
Mapy in go do not have a certain sort .
A group of elements of the type has been defined, called the key type. (...)
You will need to get all the values and keys and sort them using the sort package:
m := map[string]int{"value1": 10, "value2": 20, "value3": 30} type kv struct { k string v int } kvs := make([]kv, 0, len(m)) for k, v := range m { kvs = append(kvs, kv{k, v}) } sort.Slice(kvs, func(i, j int) bool { return kvs[i].v > kvs[j].v }) fmt.Println(kvs) Playground: https://play.golang.org/p/bk8vaGJRiou .
The examples are very similar, almost identical, but! In one case, the creation of a slice of structures is done.
var sorted_struct []key_value and in the second
kvs := make([]kv, 0, len(m))
Which is better Second? After all, if we know the size, then perhaps it is better to specify?
Source: https://ru.stackoverflow.com/questions/886632/
All Articles