How to sort map in Go in descending order?

Example:

 map[string]int{"value1": 10, "value2": 20,"value3": 30} 
  • The order of the keys in the map is not defined. And you can not swap them (this is not an array). Most likely you just need to output - so sort and output. - KoVadim

3 answers 3

Well, look, you can convert map to an array of a certain structure []struct and therefore use the function sort.Slice .

Example ( playground ):

 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.

Convert []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 .

  • @NikitaSmith These are two different data structures. Here comes Go 2.0, we'll write it ourselves. - Ainar-G
  • thank you very much! - user310533

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?